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
A P L S I I G
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".

C++:
01 class Solution {
02 public:
03     string convert(string s, int nRows) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function    
06         if(nRows==1)
07             return s;
08         int n=s.size();
09         string result;
10         for(int i=0;i<nRows;i++)
11         {
12             bool flag=false;
13             int prv=-1;
14             for(int j=i;j<n;)
15             {
16                 if(j!=prv)
17                 {
18                     result+=s[j];
19                     prv=j;
20                 }
21                 if(flag==false)
22                 {
23                     flag=true;
24                     j+=2*nRows2i*2;
25                 }
26                 else
27                 {
28                     flag=false;
29                     j+=2*i;
30                 }
31             }
32         }
33         return result;
34     }
35 };
Advertisements
This entry was posted in Array and linked list, 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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s