您的位置:首页 > 其它

leetcode: ZigZag Conversion

2013-10-15 13:47 323 查看
http://oj.leetcode.com/problems/zigzag-conversion/

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".


思路

也许有更好的做法,但是最简单的方法就是先一层层的输出,最后重新拼成一个字符串。

class Solution {
public:
string convert(string s, int nRows) {
if (1 == nRows) {
return s;
}

string result;
vector<string> rows(nRows);
int row = 0, i = 0;
bool down = true;

while (i < s.length()) {
rows[row].push_back(s[i]);
++i;

if (0 == row) {
down = true;
}
else if ((nRows - 1) == row) {
down = false;
}

if (down) {
++row;
}
else {
--row;
}
}

for (row = 0; row < nRows; ++row) {
result += rows[row];
}

return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: