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"
.
Subscribe to see which companies asked this question
这种找规律的问题应该比较适合使用归纳法进行处理,不过光用肉眼看也能看出点规律。
设i 为行号,从1开始。numRows为行数
则1到7 是(1 + 2 * numRows - 2)
2到8 是(2 + 2 * numRows - 2)
2到6是(2 + 2 * numRows - 2) - 2
3到9是(3+ 2 * numRows - 2)
3到5是(3+ 2 * numRows - 2) - 2 * 2
注意行数为1的时候应该是返回本身
class Solution { public: /* * 找规律 * 1 7 * 2 6 8 * 3 5 9 * 4 10 * */ string convert(string s, int numRows) { int len_s = s.length(); if (1 == numRows) { return s; } string res = ""; int i; for (i=0; i<numRows; i++) { int index = i; while (index < s.length()) { res += s[index]; if (1 <= i && i<(numRows-1)) { if ((index + 2 * numRows - 2 - 2 * i) < s.length()) { //cout << (index + 2 * numRows - 2 - 2 * i) << endl; res += s[index + 2 * numRows - 2 - 2 * i]; } else { break; } } index = (index + 2 * numRows - 2); } } return res; } };