leetcode: ZigZag Conversion

http://oj.leetcode.com/problems/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".

思路

也许有更好的做法,但是最简单的方法就是先一层层的输出,最后重新拼成一个字符串。

 1 class Solution {
 2 public:
 3     string convert(string s, int nRows) {
 4         if (1 == nRows) {
 5             return s;
 6         }
 7 
 8         string result;
 9         vector<string> rows(nRows);
10         int row = 0, i = 0;
11         bool down = true;
12         
13         while (i < s.length()) {
14             rows[row].push_back(s[i]);
15             ++i;
16             
17             if (0 == row) {
18                 down = true;
19             }
20             else if ((nRows - 1) == row) {
21                 down = false;
22             }
23 
24             if (down) {
25                 ++row;
26             }
27             else {
28                 --row;
29             }
30         }
31         
32         for (row = 0; row < nRows; ++row) {
33             result += rows[row];
34         }
35         
36         return result;
37     }
38 };

 

posted @ 2013-10-15 13:47  移山测试工作室黑灯老师  阅读(415)  评论(0编辑  收藏  举报
count website visits
Buy Computers