leetcode - 6.ZigZag Conversion

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

solution 1

这道题比较简单,规律比较明显。

下图中的方格表示字符,数字表示字符在字符串中的下标。

可以看到每行的数字都是有规律的。

show code

    public String convert(String s, int numRows) {
        if (numRows <= 1) {
            return new String(s);
        }
        int len = s.length();
        int step = (numRows - 1) << 1;
        char[] cs = new char[len];
        for (int i = 0, j = 0; i < numRows; i++) {
            int index = i;
            while(index < len) {
                cs[j++] = s.charAt(index);
                index += step;
                if (index % (numRows - 1) != 0 && index - (i << 1) < len) {
                    cs[j++] = s.charAt(index - (i << 1));
                } 
            }
        }
        return new String(cs);
    }

时间复杂度:,每个元素只会访问一次。
空间复杂度:。

提交代码

leetcode提交结果

你可能感兴趣的:(leetcode - 6.ZigZag Conversion)