Description
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)
And then read line by line: “PIN YLSIG YAHR PI”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Examples
Example1
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example2
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
解题思路
就是数学原理
以题目给出的例子为例,把字母转换成字符所在位置可以得到:
根据上表可以得出规律:
每两个颜色相同的块相差得值都一样,且都与numRows有关,差值 = 2 * numRows - 2
那接下来就很好做了
直接附上java代码
class Solution {
public String convert(String s, int numRows) {
if(numRows == 1)
return s;
int i, j, k;
String add, final_str = "";
ArrayList<String> temp = new ArrayList<>();
for(i = 0; i < numRows; i++){
add = "";
for(j = i; j < s.length();){
add += s.charAt(j);
j += numRows * 2 - 2;
}
temp.add(add);
}
for(i = 1; i < numRows - 1; i++){
int start = 2 * numRows - 2 - i;
k = 1;
for(j = start; j < s.length();){
temp.set(i, InsertString(k, temp.get(i), s.charAt(j)));
k += 2;
j += numRows * 2 - 2;
}
}
for(i = 0; i < temp.size(); i++){
final_str += temp.get(i);
}
return final_str;
}
public String InsertString(int pos, String str, char ch){
String ret;
ret = str.substring(0, pos) + ch;
if(pos < str.length()){
ret += str.substring(pos, str.length());
}
return ret;
}
}
其他
需要注意的是:
- 当numRows = 1的时候,需要单独考虑,否则会在判断得时候出错(2 * 1 - 2 = 0,j不会更新)
- substring(i, j)中,i是可以取到的,而j是不能取到的
- 在solution中提到了StringBuffer的使用,我不太清楚,等之后看懂了再来更新