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. 想申请一个数组的话,比如string eg[56];这样写的话所申请的数组规模必须预先给定,对于不能确定的数组,申请要动态申请,比如 string *eg = new string[num];
2. string的append和+运算的区别:append是直接在原字符串的末尾添加,+运算是生成一个新的string来存储运算结果。
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 if (numRows == 1) return s; 5 string *res = new string[numRows]; 6 int step = 1, row = 0; 7 for (char c : s) 8 { 9 if (row == 0) 10 step = 1; 11 else if (row == numRows - 1) 12 step = -1; 13 res[row] += c; 14 row += step; 15 } 16 string ans; 17 for (int i = 0; i < numRows; i++) 18 ans.append(res[i]); 19 return ans; 20 } 21 };