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"
.
Solution:
class Solution { public: string convert(string s, int nRows) { string *tmpS = new string[nRows + 1]; string ans; if(nRows < 2) return s; bool down = true; int row = 0; for(int i = 0;i < s.length();i++) { if(row == -1) { row = 1; down = true; tmpS[row] += s[i]; row++; } else if(row == nRows) { row = nRows - 2; down = false; tmpS[row] += s[i]; row--; } else { tmpS[row] += s[i]; if(down) row++; else row--; } } for(int i = 0;i < nRows;i++) ans += tmpS[i]; return ans; } };