问题链接
ZigZag Conversion | LeetCode OJ
问题描述
给出行数,将字符串PAYPALISHIRING
用曲折的方式写出来,例如行数为3,该字符串应该写作:
P A H N
A P L S I I G
Y I R
然后逐行读出来为PAHNAPLSIIGYIR
解决方法
public class Solution {
public String convert(String s, int numRows) {
if(numRows == 1){
return s;
}
String result = "";
for(int row = 0; row < numRows; row ++ ){
int step = 1;
int bottomStep = 1;
int upStep = 1;
if(row == 0||(row == numRows - 1)){
step = 2*numRows - 2;
upStep = step;
bottomStep = step;
}
else{
bottomStep = (numRows-row-1)*2;
upStep = row*2;
step = upStep;
}
for(int position = row;position < s.length();position+=step){
result += s.substring(position,position+1);
if(step != upStep){
step = upStep;
}
else if(step != bottomStep){
step = bottomStep;
}
}
}
return result;
}
}