6. 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"
.
解题思路:模拟zigzag的移动方式(竖斜竖斜竖...),用numRows个string,每次走到那个string时,在这后面把那个字符加上去。最后再把所有string拼起来就ok了
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 if(numRows==1)return s; 5 string* str=new string[numRows]; 6 int idx=0,step; 7 for(int i=0;i<s.length();i++){ 8 str[idx].push_back(s[i]); 9 if(idx==0)step=1; 10 else if(idx==numRows-1)step=-1; 11 idx+=step; 12 } 13 s.clear(); 14 for(int i=0;i<numRows;i++) 15 s.append(str[i]); 16 return s; 17 } 18 };