描述:
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"
.
代码如下:
class Solution { public: string convert(string s, int numRows){ if (numRows == 1)return s; //遇到单个字符串直接返回 string res; for (int i = 0; i < numRows; i++) //判断读入数据的位置 { for (int j = 0; j < s.length() + i; j += (numRows - 1) * 2) //每次按特定的规律叠加 { if (i != 0 && i != numRows - 1) //如果不是最开始和最后一行 { if (j - i > 0) res += s[j - i]; //存在便存入数组 if (j + i < s.length()) res += s[j + i]; } else if (j + i < s.length()) //存入一个即可 res += s[j+i]; } } return res; } };
这个题目是让人按照锯齿图形存入数据,就是按照 Z 字存入 即:
1 7 13 换成字母就是 P I N
2 6 8 12 A L S I G
3 5 9 11 Y A H R
4 10 P I
这便是把convert("PAYPALISHIRING", 3)的 3 改成 4 的排列顺序,读出的结果是 PINALSIGYAHRPI
整体的思路便是一行一行读取,到下一行的时候,在上一行的基础上读入上一行数据前后的字母
以此类推 知道最后一行