原题:
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"
.
解析:
这题发现规律后就比较好做了:
当是第一行或者最后一行字符时候,存储的字符是中间相隔的是 2 * numRows - 2(不能超过原始字符串的长度);
当是中间行的时候,分奇数行和偶数行,奇数行的时候,存储的字符是中间相隔的2 * (numRows - 1 - i),而偶数行的时候,存储的字符是中间相隔的是 2 * i;
代码: