【题目】
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"
.
将字符串锯齿状排列后获取其横排重构后的字符串;
【思路】
找规律,发现锯齿状的每一个元素与其所在的行列的关系如下:
0 | 2r-2 | 2(2r-2) | …… | ||
1 | (2r-2)-1 | (2r-2)+1 | (2*(2r-2))-1 | (2*(2r-2))+1 | …… |
2 | (2r-2)-2 | (2r-2)+2 | (2*(2r-2))-2 | (2*(2r-2))+2 | …… |
3 | (2r-2)-3 | (2r-2)+3 | (2*(2r-2))-3 | (2*(2r-2))+3 | …… |
…… | …… | …… | …… | …… | …… |
r-1 | (2r-2)-(r-1) | (2r-2)+(r-1) | (2*(2r-2))-(r-1) | (2*(2r-2))+(r-1) | …… |
【Java代码】
public class Solution_6_zigzag_convert {
public String convert(String s, int numRows){
String result = "";
if(numRows == 1){
result = s;
return result;
}
for(int i = 0 ; i < numRows&&i < s.length() ; i++){
result += s.charAt(i);
int j = 1;
if(i == 0)
while(j*(2*numRows-2)<s.length())
result += s.charAt(j++*(2*numRows-2));
else if(i == numRows - 1)
while(j*(2*numRows-2)+numRows-1<s.length())
result += s.charAt(j++*(2*numRows-2)+numRows-1);
else{
while(j*(2*numRows-2)-i<s.length()){
result += s.charAt(j*(2*numRows-2)-i);
if(j*(2*numRows-2)+i<s.length())
result += s.charAt(j*(2*numRows-2)+i);
j++;
}
}
}
return result;
}
}