解题思路
就是给定字符串,按某种特定方式排列一下。这道好像没有涉及什么算法,只是纯粹的输入输出。有些人可能不知道ZigZag到底是个什么形状,简单来说。对于字符串0123456789来说,当row = 3时的ZigZag它应该这样排列:
所以我们输出字符串0481357926.
代码
string convert(string s, int numRows) {
int n = s.size();
int m = numRows;
if (m <= 1) {
// Watch out for boundary cases.
return s;
}
int i, j;
string res = "";
for (j = 0; j < n; j += 2 * m - 2) {
res.push_back(s[j]);
}
for (i = 1; i < m - 1; ++i) {
for (j = 0; j < n; j += 2 * m - 2) {
if (j + i < n) {
res.push_back(s[j + i]);
}
if (j + 2 * m - 2 - i < n) {
res.push_back(s[j + 2 * m - 2 - i]);
}
}
}
for (j = m - 1; j < n; j += 2 * m - 2) {
res.push_back(s[j]);
}
return res;
}