LeetCode:ZigZag Conversion
6. ZigZag Conversion
Total Accepted: 78774 Total Submissions: 335842 Difficulty: Easy
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 { public: string convert(string s, int numRows) { if (numRows == 1) return s; string res = ""; int i, j; int interval = 2 * numRows - 2; for (i = 0; i<s.length();) { res = res + s[i]; i = i + interval; } for (j = 1; j<numRows - 1; j++) { int inter = 2 * j; for (i = j; i<s.length(); i = i + inter) { res = res + s[i]; inter = interval - inter; } } for (i = numRows - 1; i<s.length();) { res = res + s[i]; i = i + interval; } return res; } };