版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MyCodecOdecoDecodE/article/details/78014349
LeetCode题目:6.ZigZag Conversion
原题链接:https://leetcode.com/problems/zigzag-conversion/description/
解题思路:
对指定行row,找出逻辑,得到公式,然后进行计算即可。
核心思想:
对第一行和第row行,一个之字有两个字符,相邻字符的距离为2(row-1)。
对第i行,一个之字有三个字符,某字符到下两个字符的距离为2(row-1),相邻字符的距离为2(i-1)或2(row-i)。
依次遍历各行即可。
代码细节:
1.得到公式后,实现即可。
坑点:
1.numRows可能为1
2.输入字符串可能为空
代码:
string convert(string s, int numRows) {
string cvString; // 转换后的string
int jumpSize = 2 * (numRows - 1); // 一个字符到下一个之字型对应字符的间隔
// 特殊情况:numRows=1
if (numRows == 1) return s;
// 第一行
for (int i = 0; i < s.length(); i += jumpSize)
cvString.push_back(s[i]);
// 第二行~第numRows-1行,每个之字型中间包含一个字符,因此要取两次
for (int i = 2; i < numRows; i++) {
// 起始字符位置为i-1
int j = i - 1;
while (1) {
if (j >= s.length()) break;
cvString.push_back(s[j]);
j += jumpSize - 2 * (i - 1);
if (j >= s.length()) break;
cvString.push_back(s[j]);
j += 2 * (i - 1);
}
}
// 最后一行
for (int i = numRows - 1; i < s.length(); i += jumpSize)
cvString.push_back(s[i]);
return cvString;
}