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 in Java:
public class Solution {
public String convert(String s, int nRows) {
if(nRows==0 || nRows==1) return s;
int numRepeat = 2*nRows-2; //The number of characters in a zigzag pattern
int lengthTotal = s.length(); //The length of the original string
int nLoop = (int)Math.ceil((double)lengthTotal/(double)numRepeat); //number of loops for the zigzag pattern
String[] convertStrings = new String[nRows]; //the array of strings for n rows
for(int k=0; k<nRows; k++) convertStrings[k]="";
for(int i=0; i< nLoop-1; i++){
convertStrings[0]+= s.charAt(i*numRepeat);
convertStrings[nRows-1] +=s.charAt(i*numRepeat + nRows-1);
for(int j=1; j< nRows-1; j++){
convertStrings[j]= convertStrings[j]+ s.charAt(i*numRepeat+ j) + s.charAt((i+1)*numRepeat-j);
}
}
//The code for the last loop, which may contain less than numRepeat characters
convertStrings[0]+= s.charAt((nLoop-1)*numRepeat);
for(int j=1; j< nRows-1; j++){
if((nLoop-1)*numRepeat +j < lengthTotal && (nLoop)*numRepeat -j <lengthTotal )
convertStrings[j]= convertStrings[j]+ s.charAt((nLoop-1)*numRepeat+ j) + s.charAt(nLoop*numRepeat-j);
else if((nLoop-1)*numRepeat+j<lengthTotal)
convertStrings[j] += s.charAt((nLoop-1)*numRepeat+j);
}
if((nLoop-1)*numRepeat + nRows-1<lengthTotal)
convertStrings[nRows-1] +=s.charAt((nLoop-1)*numRepeat + nRows-1);
String converted="";
for(int k=0; k<nRows; k++){
converted+= convertStrings[k];
}
return converted;
}
}
Note:在zigzag的pattern下,可以将字符串分为多组,每一组长度为nRows*2-2,既为除了第一行和最后一行,每一行都要经过两遍。建立大小为nRows的String数组,每组保存相对应一行的字符串,遍历整个字符串s,赋值时将该位置的字符串联到相应的行中,最后几行串联为完整的字符串。
字符串和char串联,一样可以用‘+’号。
提取字符串中某一位的char,不能直接用s[index]这种方法,此时s被默认为数组。要用s.charAt(index)函数。
向上取整用Math.ceil(double x)函数,返回值也为double。
注意最后一个loop时要特别处理,因为字符串张度可能不是nRows*2-2的整数倍,这时要检查index是否已超过字符串总长。