ZigZag Conversion
题目描述
输入一个字符串s和一个正整数n。将s按照长度为n的Z字形排列。按行输出Z字形字符串。
写不清楚,自己去看LeetCode吧。
分析
直观的两个方法
- 模拟
- 看出每一行的下标的规则
看出规则应该比较简单,也没有空间复杂度,O(n)。
第一行和最后一行(hang)为一波,中间那几行(hang)为一波。
代码
class Solution {
public:
string convert(string s, int numRows) {
int len = s.size(), cur = 0;
string res = "";
if (numRows == 1)
return s;
// line 1
res.append(s.substr(0, 1));
cur = 0;
while (cur + numRows * 2 - 2 < len)
{
cur = cur + numRows * 2 - 2;
res.append(s.substr(cur, 1));
}
// line 2 to line n - 1
for (int i = 1; i < numRows - 1; i++)
{
cur = i;
if (cur < len)
res.append(s.substr(cur, 1));
while (cur + numRows * 2 - 2 - 2 * i < len)
{
res.append(s.substr(cur + numRows * 2 - 2 - 2 * i, 1));
cur = cur + numRows * 2 - 2;
if (cur < len)
res.append(s.substr(cur, 1));
}
}
// line n
cur = numRows - 1;
if (cur < len)
res.append(s.substr(cur, 1));
while (cur + numRows * 2 - 2 < len)
{
cur = cur + numRows * 2 - 2;
res.append(s.substr(cur, 1));
}
return res;
}
};
思考
这个题像一个凑数的题,没啥意义