题目名称:6. ZigZag Conversion
题目难度:Medium
题目描述:
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
.
题目分析:
题目并没有说清楚zigzag样式到底是一个什么样的样式,查了一下才知道是这样子的:
Δ=2n-2 1 2n-1 4n-3
Δ= 2 2n-2 2n 4n-4 4n-2
Δ= 3 2n-3 2n+1 4n-5 .
Δ= . . . . .
Δ= . n+2 . 3n .
Δ= n-1 n+1 3n-3 3n-1 5n-5
Δ=2n-2 n 3n-2 5n-4
于是就有了思路,很直接地用一个二维矩阵保存起来,然后再按要求输出就行,比较需要注意的是矩阵的大小,可以使用压缩处理将中间一些比较稀疏的列合在一起。
最后AC的代码是:
class Solution {
public:
string convert(string s, int numRows) {
if (s.size() <= 1 || numRows == 1) return s;
int numCols;
if (s.size() <= numRows) {
numCols = 1;
} else {
int t = numRows * 2 - 2;
int temp = s.size() / t * 2;
int toIf = s.size() % t;
if (toIf < numRows) numCols = temp + 1;
else numCols = temp + 2;
}
vector<char> temp(numCols, '-');
vector<vector<char>> v;
v.assign(numRows, temp);
int index = 0;
bool flag = 0;
for (int j = 0; j < numCols; ++j) {
if (j % 2 == 0) {
for (int i = 0; i < numRows; ++i) {
v[i][j] = s[index++];
if (index >= s.size()) {
flag = 1;
break;
}
}
} else {
for (int i = numRows - 2; i > 0; --i) {
v[i][j] = s[index++];
if (index >= s.size()) {
flag = 1;
break;
}
}
}
if (flag) break;
}
string result;
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numCols; ++j) {
if (v[i][j] != '-') {
result += v[i][j];
}
}
}
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numCols; ++j) {
cout << v[i][j] << ' ';
}
cout << endl;
}
cout << endl;
return result;
}
};