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 NA P L S I I GY 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"
.
思路:
1、numRows可以计算出每多少个字母一个循环(例如,上面例子中为4个字母一个循环)
2、竖直的字符个数为numRows,斜杠部分的字符个数实际上是numRows - 2,每(numRows * 2 - 2)个数字一个循环
3、每次偏移量增加(numRows * 2 - 2),依次输出即可。判断该位置是否有字符的唯一标准为是否越界,so easy
源代码如下:
#include#include #include using namespace std;class Solution {public: string convert(string s, int numRows) { if (numRows == 1) return s; string strResult; int iLen = s.size(); int iCellNum = numRows * 2 - 2; for (int i = 0; i < numRows; ++i) { if (i == 0 || i == numRows - 1) { int j = i; while (j < iLen) { strResult += s[j]; j += iCellNum; } } else { int j = i; int k = iCellNum - i; while (j < iLen) { strResult += s[j]; j += iCellNum; if (k < iLen) { strResult += s[k]; k += iCellNum; } } } } return strResult; }};int main(){ Solution a; string strResult = a.convert("PAYPALISHIRING", 3); printf("%s\n", strResult.c_str()); system("pause"); return 0;}