6. ZigZag Conversion

1. Description

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)
It is hard to present that picture using markdonw
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);

2. Example

Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”

Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”

Example 3:
Input: s = “A”, numRows = 1
Output: “A”

3. Constraints

  • 1 <= s.length <= 1000
  • s consists of English letters (lower-case and upper-case), ‘,’ and ‘.’.
  • 1 <= numRows <= 1000

4. Solutions

Analyze

n = str.size()
Time complexity: O(n)
Space complexity: O(1)

class Solution {
public:
    string convert(const string &str, int rows) {
        if(rows == 1 || rows >= str.size()) {
            return str;
        }

        string result(str.size(), 0);
        const int circle = 2 * rows - 2;
        for (int line = 0, index = 0; line < rows; ++line) {
            int diff = (rows - (line + 1)) * 2;
            for (int i = line; i < str.size(); i += circle) {
                result[index++] = str[i];

                if (0 < line && line < rows - 1 && i + diff < str.size()) {
                    result[index++] = str[i + diff];
                }
            }
        }

        return result;
    }
};
Last updated:
Tags: String
comments powered by Disqus