https://leetcode.com/problems/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 s, int numRows); Example 1: Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR" Example 2: Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I
class Solution { public: string convert(string s, int numRows) { } };
00 12 01 11 13 02 10 14 03 09 15 21 04 08 16 20 05 07 17 19 06 18
class Solution { public: string convert(string s, int numRows) { if (numRows == 1){ return s; } string solution = s; int solutionIdx = 0; int period = numRows -1; int charIdx = 0; while (charIdx < s.size()){ solution[solutionIdx] = s[charIdx]; solutionIdx ++; charIdx += period * 2; } for (int rowIdx = 1; rowIdx < numRows -1; rowIdx ++){ charIdx = rowIdx; while (charIdx < s.size()){ solution[solutionIdx] = s[charIdx]; solutionIdx ++; int charIdx2 = charIdx + 2 * (numRows -1 - rowIdx) ; if (charIdx2 < s.size()){ solution[solutionIdx] = s[charIdx2]; solutionIdx ++; } charIdx += period * 2; } } charIdx = numRows -1; while (charIdx < s.size()){ solution[solutionIdx] = s[charIdx]; solutionIdx ++; charIdx += period * 2; } assert(solutionIdx == s.size()); assert(solution.size() == s.size()); return solution; } };