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:
This problem is straightforward and it test our string processing ability and logical thinking. For the first row and last row, we only need to add zig chars, for the middle rows, we need to add both zig and zag chars. Zig char index: j and next one is j+2*(nRows-1));zag char index: j+2*(nRows-i-1)) . For instance, the second row of giving example, j=1, A: 1, P:1+2*(3-1-1)=3, L: 1+2*(3-1)=5, S: 5+2*(3-1-1)=7....
The time complexity is: O(n) because each char is only visited once.
public String convert(String s, int nRows) {
if(s==null || s.length()==0 || nRows<=1 || s.length()<=nRows) return s;
StringBuilder sb=new StringBuilder();
for(int i=0;i<nRows;i++){
int j=i;
while(j<s.length()){
sb.append(s.charAt(j));
if(i!=0 && i!=nRows-1 && (j+2*(nRows-i-1))<s.length()) sb.append(s.charAt(j+2*(nRows-i-1)));
j=j+2*(nRows-1);
}
}
return sb.toString();
}
No comments:
Post a Comment