这题没什么意思,就是纯粹的找规律。
发现所有行的重复周期都是 2 * nRows - 2
对于首行和末行之间的行,还会额外重复一次,重复的这一次距离本周期起始字符的距离是 2 * nRows - 2 - 2 * i
class Solution {
public:
string convert(string s, int nRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
string result;
if (nRows < 2) return s;
for (int i = 0;i < nRows;++i) {
for (int j = i;j < s.length();j += 2 * (nRows - 1)) {
result.push_back(s[j]);
if (i > 0 && i < nRows - 1) {
if (j + 2 * (nRows - i - 1) < s.length())
result.push_back(s[j + 2 * (nRows - i - 1)]);
}
}
}
return result;
}
};
本文介绍了一种将字符串以Z形排列方式重新组织的算法实现。通过观察Z形排列的规律,采用C++语言编写了一个解决方案。该算法考虑了不同行数情况下的字符串转换,并通过循环迭代完成字符串的重新组织。
197

被折叠的 条评论
为什么被折叠?



