标签:
描述:
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"
.
观察
0 | 8 | |||
1 | 7 | 9 | ||
2 | 6 | 10 | ||
3 | 5 | 11 | ||
4 | 12 |
要处理的是两部分,直线0-1-2-3-4和斜线5-6-7,后面的都是这两个的重复,创建一个String数组ans=new String[nRows]保存每行的字母,然后两个循环,一个for循环处理直线,一个处理斜线
for(j=0;i<s.length()&&j<nRows;j++){
ans[j]+=s.charAt(i);
i++;
}
for(j=nRows-2;j>0&&i<s.length();j--){
ans[j]+=s.charAt(i);
i++;
}
i表示原始字符串的下标,当i到达末尾时循环结束,这种方法简单易于理解,而且时间复杂度O(n).
1 public String convert(String s, int nRows) { 2 if(s.length()<=nRows||nRows==1) //特殊情况处理 3 return s; 4 int i=0,j=0; 5 int nRows_minus_ends=nRows-2; 6 String[] ans=new String[nRows]; 7 for(int k=0;k<ans.length;k++) 8 ans[k]=""; 9 while(i<s.length()){ 10 for(j=0;i<s.length()&&j<nRows;j++){ 11 ans[j]+=s.charAt(i); 12 i++; 13 } 14 for(j=nRows_minus_ends;j>0&&i<s.length();j--){ 15 ans[j]+=s.charAt(i); 16 i++; 17 } 18 } 19 String ansString=""; 20 for(int k=0;k<ans.length;k++) 21 ansString+=ans[k]; 22 return ansString; 23 }
标签:
原文地址:http://www.cnblogs.com/duanqiong/p/4431690.html