题目描述:
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"
.
本题要求我们将字符串按照上述的规律排列,返回重新排列后的新的字符串。
解题思路:
本题只要找到规律,问题就迎刃而解了。以本题给我们的例子为例,首先,将P、A等等开头的竖列看为主列,它们之间的规律是:每行相间的两个数相差2*numRows-2。其次是像P、S、I这样在主列之间的字符,它们的规律是:下一个主列的字符的位置-2*(所在行数-1)。
代码:
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 int n=s.length(); 5 if(n<=2||numRows<2) 6 return s; 7 int gap=2*numRows-2; 8 string result=""; 9 for(int i=0;i<numRows;i++){ 10 for(int j=i;j<n;j+=gap){ 11 result+=s[j]; 12 if(i>0&&i<numRows-1){ 13 int t=j+gap-2*i; 14 if(t<n) 15 result+=s[t]; 16 } 17 } 18 } 19 return result; 20 } 21 };