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"
.
Solution:
find the mathematical relations of characters in the string.
the distance between each red character (such as "A" to "L")in same row is 2*(nRows-1);
there is at most one intermediate char in two red chars, the distance from A to P is 2*(nRows- 1- i), i is the current row number(from 0 to nRows);
刚开始没有看清题目,当成只有3行来解了。
画出nRows=4, nRows=5时的图,总结出数学关系求解即可。
注意边界条件,否则无法通过OJ(漏写了nRwos为1时的情况)。
public class Solution {
public String convert(String s, int nRows) {
// Start typing your Java solution below
// DO NOT write main() function
if(s==null){
return null;
}
int len = s.length();
// must consider the bounday conditions.
if(nRows <= 1){
return s;
}
StringBuffer sb = new StringBuffer();
for(int i=0; i<nRows; i++){
int j = i;
while(j<len){
sb.append(s.charAt(j));
if(i%(nRows-1) != 0){
int k= j + 2*(nRows-1-i);
//use k as an "intermediate" between 2 characters in same horizontal line.
if(k<len){
sb.append(s.charAt(k));
}
}
j += 2*(nRows-1);
//distance between the character which in the same horizontal line,
//but in different vertical lines.
}
}
return sb.toString();
}
}