题目:
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"
Zigzag:即循环对角线结构(
0 | 8 | 16 | |||||||||
1 | 7 | 9 | 15 | 17 | |||||||
2 | 6 | 10 | 14 | 18 | |||||||
3 | 5 | 11 | 13 | 19 | |||||||
4 | 12 | 20 |
)
nRows行,声明nRows个字符串,每个字符串存储自己行的字符
向下循环:nRows
斜角线向上循环: 从nRows-2 开始,1 结束 (减去首尾两个端点)
重复
...
1
2
3
4
5
6
7
8
9
10
11
12
13
|
string
convert(string s, int nRows){ if (nRows
== 1) return s; string
res[nRows]; int i
= 0, j, gap = nRows-2; while (i
< s.size()){ for (j
= 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];//垂直向下循环 for (j
= gap; i < s.size() && j > 0; --j) res[j] += s[i++];//向上循环 } string
str = "" ; for (i
= 0; i < nRows; ++i) str
+= res[i]; return str; } |
法二:
每次把由字母排列成的一个 V 形状 ,当一个循环,每个循环之间相差 2(numRows-1),如上面 Zigzag:即循环对角线结构 中的 0与8 相差2(5-1)
不同的行i 所有 对应的差值 就是 2(numRows-i -1),相当于行数减少了,减少到了numRows-i行。
注意:numRows小于2时,差值为0
java版本
public class Solution {
public String convert(String s, int numRows) {
if(s.length()<=2 || numRows<2)
return s;
String ret="";
int distance=2*(numRows-1);
for(int i=0;i<numRows;i++){
for(int j=i;j<s.length();j=j+distance){
ret=ret+s.charAt(j);
if(i!=0 && i!=numRows-1 && j+ (distance-2*i) < s.length())
ret=ret+ s.charAt( j+ (distance-2*i) ) ;
}
}
return ret;
}
}