文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
ZigZag Conversion2. Solution
- Version 1
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1 || s.length() <= numRows) {
return s;
}
string result;
vector<string> lines(numRows);
int row = -1;
bool flag = true;
for(char ch : s) {
row = flag?++row:--row;
lines[row] += ch;
if(row == 0) {
flag = true;
}
else if(row == numRows - 1) {
flag = false;
}
}
for(string line : lines) {
result += line;
}
return result;
}
};
- Version 2
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1 || s.length() <= numRows) {
return s;
}
string result;
vector<string> lines(numRows);
int row = -1;
int step = 1;
for(char ch : s) {
row += step;
lines[row] += ch;
if(row == 0) {
step = 1;
}
else if(row == numRows - 1) {
step = -1;
}
}
for(string line : lines) {
result += line;
}
return result;
}
};
网友评论