leetCode 6:ZigZag Conversion
題目:
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 R
And 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”
分析:
本題是對字符串進行操作,本質上是一道數學題,需要找到字符分佈的相應規律,通過對zigzag的瞭解,以及推算證明,得到每行字符的分佈規律,第一行和最後一行字符間隔爲2*(numRows-1),而中間行字符間隔的規律則與所在列相關,假如所在列爲奇數列,則下一字符間隔爲2*(numRows-i-1);若所在列爲偶數列,則下一字符間隔爲2i.這一規律可以通過畫圖直觀的得到,第一行與最後一行的相鄰兩個頂點構成一個類似v的形狀,而對於中間行,分佈在v的中間部分,間隔爲v下方頂點數加1或上方頂點數加1.
代碼:
public class ZigZag {
public static String convert(String s,int numRows){
if(numRows<=1||s.length()==0)
return s;
int len=s.length();
int step=2*(numRows-1);
String res="";
for(int i=0;i<len && i<numRows;++i){
int indx=i;
res +=s.charAt(indx);
for(int j=1;j<len;++j){
if(i==0 || i==numRows-1){
indx +=step;
}else{
if(j % 2 != 0)
indx +=2*(numRows-1-i);
else
indx +=2*i;
}
if(indx<len)
res +=s.charAt(indx);
}
}
return res;
}
public static void main(String[] args){
String s="PAYPALISHIRING";
String result=convert(s,3);
System.out.println("轉換後的字符串爲:"+result);
}
}