【LeetCode】6. ZigZag Conversion(C++)
阿新 • • 發佈:2018-12-21
題目:
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)
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 s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
理解:
把給定的字串按zigzag的形式寫出來,然後按行輸出。下面是我的實現。
實現:
class Solution { public: string convert(string s, int numRows) { if(numRows==1) return s; string res; for (int i = 0; i < numRows; ++i) { for (int j = i;;) { if (i != numRows - 1) { res += s[j]; j += 2 * numRows - 2 - 2 * i; if (j >= s.size()) break; } if (i != 0) { res += s[j]; j += 2 * i; if (j >= s.size()) break; } } } return res; } };