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.每个‘n’就是一个循环,位置都是可以计算出来的
2.用一个flag来记录位置,通过改变step =1 OR step = -1来更改方向
代码:C++ 思路1:
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) return s; vector<string> str (numRows,""); string solve = ""; int row = 0; int row_max = numRows - 1; int mod = 2 * numRows - 2; for (int i = 0; i < s.length(); i++) { row = row_max - abs(i % mod - row_max); str[row] += s[i]; } for (int i = 0; i < numRows; i++) { solve += str[i]; } return solve; } };