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 RAnd 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"
.
[Analysis]
直接看几个例子就知道该怎么做了:
ABCDEFGHIJKLMNOP 2
A C E G I K M O
B D F H J L N P
ABCDEFGHIJKLMNOP 4
A G M
B F H L N
C E I K O
D J P
ABCDEFGHIJKLMNOP 5
A I
B H J P
C G K O
D F L N
E M
[Solution]
class Solution {
public:
string convert(string s, int nRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// only one row
if(nRows == 1){
return s;
}
// more than one rows
int j = 0, k = 0; // jth column, k letters has been writen
string column;
// the matrix stores the zigzag writen letters
vector<string> matrix;
while(k < s.length()){
// the zigzag column, if nRows=2, it should not be zigzag writen
if(j % 2 == 1 && nRows > 2){
column = " ";
// out of range
if(nRows - 2 + k > s.length()){
column += s.substr(k, s.length() - k);
k += s.length() - k;
// fill remaining spaces
column += string(nRows - column.length(), ' ');
}
else{
column += s.substr(k, nRows - 2);
k += nRows - 2;
column += " ";
}
// reverse
reverse(column.begin(), column.end());
matrix.push_back(column);
}
else{
if(nRows + k > s.length()){
column = s.substr(k, s.length() - k);
k += s.length() - k;
}
else{
column = s.substr(k, nRows);
k += nRows;
}
matrix.push_back(column);
}
j++;
}
// generate result
string res = "";
for(int i = 0; i < nRows; ++i){
for(j = 0; j < matrix.size(); ++j){
// filter spaces
if(matrix[j].size() > i && matrix[j][i] != ' '){
res += matrix[j][i];
}
}
}
return res;
}
};
说明:版权所有,转载请注明出处。 Coder007的博客