将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “PAYPALISHIRING” 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"
class Solution {
public:
string convert(string s, int numRows) {
if(numRows == 1 || s.length() == 1)
return s;
vector<vector<char>> matrix(numRows,vector<char>(s.length()/2 + 1));
int k = 0, i = 0, j=0;
while(k < s.length()){
for(;(i < numRows) && (k < s.length()); i++){
matrix[i][j] = s[k];
k++;
}
i--;
i--;j++;
for(;(i > 0) && (k < s.length()); i--,j++){
matrix[i][j] = s[k];
k++;
}
}
string output = "";
vector<vector<char>>::iterator row_it;
vector<char>::iterator col_it;
for(row_it = matrix.begin();row_it != matrix.end();row_it++){
for(col_it = (*row_it).begin();col_it < (*row_it).end();col_it++){
if(*col_it != NULL)
output += *col_it;
}
}
return output;
}
};
感觉写的比较啰嗦,但也不知道怎么改。还有边界意识,提交了三次修修改改才过。我们看看官方的。
//模仿添加的过程
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
vector<string> rows(min(numRows, int(s.size())));
int curRow = 0;
bool goingDown = false;
for (char c : s) {
rows[curRow] += c;
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
string ret;
for (string row : rows) ret += row;
return ret;
}
};
//数学归纳法
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s;
string ret;
int n = s.size();
int cycleLen = 2 * numRows - 2;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j + i < n; j += cycleLen) {
ret += s[j + i];
if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
ret += s[j + cycleLen - i];
}
}
return ret;
}
};