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"
.
设置标记zigzag,当它为true时从上往下添加;当它为false时从下往上添加
每次修正当前行,到第一行和最后一行时修正的偏移量为2
class Solution {
public:
string convert(string s, int nRows) {
if( s == "" || nRows <= 1)
return s;
vector< string> con( nRows, string());
int i = 0;
int r = 0;
int zigzag = true;
while( i < s.size()){
if( zigzag){
con[r++] += s[i++];
}
else{
con[r--] += s[i++];
}
if( r == nRows){
zigzag = false;
r -= 2;
}
if( r < 0){
zigzag = true;
r += 2;
}
}
string res = "";
for( int i = 0; i < con.size(); ++i)
res += con[i];
return res;
}
};