ZigZag Conversion
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"
.
思路:这题主要找规律,首先定一个string的vector变量str,在nRows范围内有str[j]=str[j]+s[i],即将在每一行的一个字符放入相应的str[j],j>=0&&j<nRows,然后当j==nRows的时候,这个时候又要有这样的变化,从nRows-2开始,反方向搜索。直到所有的字符放入对应的str[j]内。
class Solution { public: string convert(string s, int nRows) { if(s.size()<=0||nRows<=1) return s; vector<string> str(nRows); str.clear(); int n=s.size(); int i=0,j=0; while(i<n) { while(i<n&&j<nRows) { str[j]=str[j]+s[i]; i++; j++; } j=nRows-2;//倒数第二行开始 while(j>0&&i<n) { str[j]=str[j]+s[i]; i++; j--; } } string result=""; for(i=0;i<nRows;i++) { result=result+str[i]; } return result; } };