题目:
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"
.
思路:
本题感觉题意上的理解就会使很多人陷入误区,首先分析题意的核心词汇是:written in a zigzag pattern on a given number of rows)在给定的行数上以锯齿形的方式写),所以上述例子可以写成这样:
- P.......A........H.......N
- ..A..P....L..S....I...I....G
- ....Y.........I........R
代码:
class Solution {
public:
string convert(string s, int numRows) {
if(numRows<=1)
return s;
vector<string> str(numRows,"");
int step,row=0;
for(int i=0;i<s.size();i++)
{
str[row].push_back(s[i]);
if(row==0)
step=1;
else if(row == numRows-1)
step=-1;
row+=step;
}
s.clear();
for(int j=0;j<numRows;j++)
{
s.append(str[j]);
}
return s;
}
};