标签:
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"
.所以,代码如下:
1 public String convert(String s, int numRows) { 2 if(s == null || s.length() <= numRows || numRows == 1){ 3 return s ; 4 } 5 StringBuilder res = new StringBuilder() ; 6 char [] arr = s.toCharArray() ; 7 int period = 2*numRows - 2 ; 8 for(int i = 0 ; i < numRows ; i++){ 9 for(int j = i ; j < s.length(); j += period){ 10 if((period-i)%period != i){ 11 res.append(arr[j]) ; 12 if((j+period-2*i) < s.length()){ 13 res.append(arr[j+period-2*i]) ; 14 } 15 }else{ 16 res.append(arr[j]) ; 17 } 18 } 19 } 20 21 return res.toString() ; 22 }
标签:
原文地址:http://www.cnblogs.com/mukekeheart/p/5704315.html