LeetCode Algorithm 06_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".

 

Tags: String

 

分析:

(1)此题要求返回string,可以利用string = string+char 的方式实现可变长string。

(2)此题没有要求打印出表格中的分布结构,故可以不考虑列分布,每行用一个字符串接收逐渐落在自己行内的字符。当行数i未到达最大行nRows-1时,字符串"|"分布,i++;

当行数达到nRows-1时,字符串开始"/"分布,i--。

 

c++代码:

 1 class Solution {
 2 public:
 3     string convert(string s, int nRows) {
 4         if (nRows <= 1)
 5             return s;
 6         vector < string > zigzag(nRows, "");
 7         //此处也可以直接用字符串数组string zigzag[nRows];来声明
 8         int len = s.length();
 9         int k = 0; //约束字符串长度
10         int i = 0; //约束行
11         while (k < len) {
12             if (i == nRows - 1) {
13                 //此处是给最后一行字符串更新
14                 zigzag[i] += s[k++];
15                 //此处接着把字符串沿"/"方向分布,直到第一行(不包括)
16                 for (i = i - 1; i > 0 && k < len; i--) {
17                     zigzag[i] += s[k++];
18                 }
19             } else {
20                 //此处把字符串沿着"|"方向分布,直到最后一行(不包括)
21                 zigzag[i] += s[k];
22                 i++;
23                 k++;
24             }
25         }
26         string result = "";
27         //跟前面一样,字符串加字符赋值自身实现可变长string效果
28         for (int i = 0; i < nRows; i++) {
29             for (int j = 0; j < zigzag[i].length(); j++) {
30                 result += zigzag[i][j];
31             }
32         }
33         return result;
34     }
35 };

 

posted @ 2015-03-22 00:56  CHEN0958  阅读(105)  评论(0编辑  收藏  举报