【字符串】6. Z 字形变换

题目:

解答:

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) 
 4     {
 5            if (numRows == 1) 
 6         {
 7             return s;
 8         }
 9 
10         // 防止s的长度小于行数
11         vector<string> rows(min(numRows, int(s.size()))); 
12         int curRow = 0;
13         bool goingDown = false;
14 
15         for (char c : s) 
16         {
17             rows[curRow] += c;
18             if (curRow == 0 || curRow == numRows - 1) 
19             {
20                 // 当前行curRow为0或numRows -1时,箭头发生反向转折
21                 goingDown = !goingDown;
22             }
23             curRow += goingDown ? 1 : -1;
24         }
25 
26         string ret;
27         for (string row : rows) 
28         {
29             // 从上到下遍历行
30             ret += row;
31         }
32 
33         return ret;
34     }
35 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12825520.html