ZigZag Conversion
ioleon13 opened this issue · comments
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".
思路:使用二维字符数组保存zigzag转换出来的字符串,其他位置使用0填充。通过nRows得出一次完整zigzag需要的元素个数nZigZagLen = 2 * nRows - 2,所以将字符串转换为zigzag字符串需要的循环次数nZigZagCount = string.len/nZigZagLen
每一次zigzag循环,矩阵中斜线部分字符的填充:
for(int i = 0; i < nRows-2; ++i) {
matrix[nRows-2-i][nZigZagPos*(nRows-1)+1+i] = s[nPos]; //nZigZagPos是上一层nZigZagCount循环的下标
nPos++;
}