ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"


Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

01 string convert(string s, int nRows) {
02        if(nRows<=1)
03            return s;
04        int n=s.size();
05        if(n==0)
06            return s;
07        string tmp[nRows];
08        for(int i=0;i<n;i+=2*nRows2){
09            tmp[0]+=s[i];
10            if(i+nRows1<n)
11               tmp[nRows1]+=s[i+nRows1];
12            for(int j=1;j<=nRows2;j++){
13               if(i+j<n)
14                   tmp[j]+=s[i+j];
15               int m=i+j+2*nRows2*(j+1);
16               if(m<n)
17                   tmp[j]+=s[m];
18            }
19        }
20        string result;
21        for(int i=0;i<nRows;i++)
22            result+=tmp[i];
23        return result;
24 }
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s