Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 6. Zigzag Conversion

Rain Hu

6. Zigzag Conversion


一、題目

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to dispaly this pattern in a fixed font for better legibility)
\( \quad\texttt{P A H N}\\ \quad\texttt{APLSIIG}\\ \quad\texttt{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:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Array

string convert(string s, int numRows) {
    if (numRows == 1) return s;
    vector<string> rows(numRows);
    int unit = 1;
    int k = 0;
    for (int i = 0; i < s.length(); i++) {
        if (k + unit == numRows || k + unit == -1)
            unit *= -1;
        rows[k].push_back(s[i]);
        k += unit;
    }
    
    string res;
    for (string& s : rows) res += s;
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[Leetcode] 7. Reverse Integer
Next
[LeetCode] 5. Longest Palindromic Substring