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".

思路:

最开始题意理解不清楚,后来看了下面这组图以后就明白了,找规律解决即可。

nRows = 2
0 2 4 6 8
1 3 5 7 9
nRows = 3
0   4   8     12    16
1 3 5 7 9  11 13 15
2   6   10    14
nRows = 4
0     6       12       18
1   5 7    11 13    17 19
2 4   8 10    14 16
3     9       15

代码:

 1     string convert(string s, int nRows) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.  
 4         if(nRows == 1)
 5             return s;  
 6         vector<string> tmp(nRows,"");
 7         int step = 0, cur = 0;
 8         int l = s.length();
 9         while(cur < l){
10             if(step == 0){
11                 int i;
12                 for(i = 0; i < nRows && cur+i < l; i++)
13                     tmp[i] += s[cur+i];
14                 if(i < nRows)
15                     break;
16                 cur += nRows;
17             }
18             else{
19                 tmp[nRows-1-step] += s[cur];
20                 cur++;
21             }
22             step = (step+1)%(nRows-1);
23         }
24         string result = "";
25         for(int i = 0; i < nRows; i++)
26             result += tmp[i];
27         return result;
28     }

 

posted on 2013-11-11 20:33  waruzhi  阅读(211)  评论(0编辑  收藏  举报

导航