--

leetcode 006: zigzag conversion



https://leetcode.com/problems/zigzag-conversion/



problem:
  
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



start code (c++)
class Solution {
public:
    string convert(string s, int numRows) {
    
        
    }
};



solution 1:

我的思路:
我们首先可以把 zigzag 改写一下,好用来判断

00      12
01  11  13
02  10  14
03  09  15  21
04  08  16  20
05  07  17  19
    06      18


总体而言,有两种思路,一种是对于 solutionStr 的 charIdx 进行遍历,填充
另外一种是对于 s 的 charIdx 进行遍历,
相对而言,前面一种略微简单一点,我们可以对于 solution 按照行进行处理,除了开头一行和最后亚航有点特殊需要单独处理之外,中间的行可以统一处理。

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;
    }
};