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"
.第一个考虑的问题是如果 nRows 比 input长度还小怎么办 (极端情况是负数)。保险起见还是先check condition.
总体思路的话, 我用了两个Int 当指针。 一个指示正常规律的跳跃一个指示zigzag。 设置了一个常数代表跳跃变量。 注意的问题是当跳跃变量等于0时容易死循环。。。
CODE:
public class Solution {
public String convert(String s, int numRows) {
String ret = "" ;
int len = s.length() ;
int c = 2 * numRows - 2 ;
if(c != 0 && 0 < numRows && numRows < len){
for(int i = 0; i < numRows ; i++){
ret += s.charAt(i);
int index = i + c ;
int zig = c - i ;
while(index < len || zig < len){
if(i != 0 && i != (numRows -1)){
ret += s.charAt(zig);
}
if(index < len) ret += s.charAt(index);
zig += c ;
index += c ;
}
}
} else{
ret = s;
}
return ret;
}
}
No comments:
Post a Comment