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 RAnd 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"
.
题解:
n=2时,字符串坐标变成zigzag的走法就是:
0 2 4 6
1 3 5 7
n=3时的走法是:
0 4 8
1 3 5 7 9
2 6 10
n=4时的走法是:
0 6 12
1 5 7 11 13 (j = 1 5 = 1+ 2n-2 - 2*1, j = 5 11 = 5 + 2n-2 - 2*1)
2 4 8 10 14
3 9 15
可以发现规律,每个zigzag包含2n-2个字符 第一行和最后一行,就是按照2n-2的顺序一点点加的。
对于除了第一行最后一行的行数值为 j+(2n-2)-2i(i是行的index)。
所有字符走一遍 时间O(n)
所有字符走一遍 时间O(n)
public class Solution { public String convert(String s, int numRows) { if (s == null || s.length() == 0) { return s; } if (numRows == 1) { return s; } StringBuilder res = new StringBuilder(); int size = 2*numRows - 2; for (int i = 0; i < numRows; i++) { for (int j = i; j < s.length(); j += size ) { res.append(s.charAt(j)); if (i != 0 && i != numRows - 1 && j + size - (i * 2) < s.length()) { res.append(s.charAt(j + size - (i * 2))); } } } return res.toString(); } }
没有评论:
发表评论