6. ZigZag Conversion

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

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

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

algorithm thought

开始拿到这个题的时候,想法是直接构造一个二维数组,按照zigzag顺序把字符串存入其中。但是这种方法太慢了,也太占用空间了,很多地方都没有存数据。

于是开始找规律,发现除了第一行和最后一行。中间每行都是两个纵向字符中夹着一个。首先找纵向字符的规律,每一行两个纵向字符位置差是,numRows*2-2。然后再找到中间夹着的字符是如何分布的。

code

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1)
            return s;
        string res="";
        int step=numRows*2-2;
        int step2=step;
        for(int i=0;i<numRows;++i){
            int j=i;
            if(j>=s.size())
                return res;
            res.push_back(s[j]);
            while(true){
                if(i!=0&&i!=numRows-1){
                    if(j+step2<s.size())
                        res.push_back(s[j+step2]);
                    else
                        break;
                }
                if(j+step<s.size())
                    res.push_back(s[j+step]);
                else
                    break;
                j+=step;
            }
            step2-=2;
        }
        return res;
    }
};

algorithm analysis

虽然函数中是双重循环,但是子循环的步数很大。整个算法只需要遍历一遍字符串即可,时间复杂度是O(n)

Last updated