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"
.
Have you met this question in a real interview?
Yes
No
思路: 题目有些唬人,其实就是建立nRows个string,然后按照Z的方式一个一个的将字符加到string后面。 就是判断是从上往下添加到行还是从下往上添加到行的问题。
class Solution {
public:
string convert(string s, int nRows) {
if(nRows==1) return s; //注意判断
string *str = new string[nRows];
int i, row=0;
bool upToDown = true;
for(i=0;i<s.length();i++){
if(upToDown){
str[row++]+=s[i];
if(row==nRows){
upToDown = false;
row-=2;
}
}else{
str[row--]+=s[i];
if(row==-1){
upToDown = true;
row+=2;
}
}
}
string ans;
for(i=0;i<nRows;i++)
ans+=str[i];
return ans;
}
};