Jerry's Blog

Recording what I learned everyday

View on GitHub


19 December 2019

LeetCode(66) -- 6

by Jerry Zhang

P6. ZigZag Conversion (Medium)

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”

我的思路

0           8               16
1        7  9           15  17
2     6     10      14      18
3  5        11  13          19
4           12              20

这样找规律,每一列相差都是8,除了第一行和最后一行,中间还会有一些插入的数,间隔是等差数列。

我的代码

class Solution {
    public String convert(String s, int numRows) {
        char[] chars = s.toCharArray();
        int step = numRows == 1 ? 1 : (numRows - 1) * 2;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            int j = i;
            if (i == 0 || i == numRows - 1) {
                while (j < chars.length) {
                    sb.append(chars[j]);
                    j += step;
                }
            } else {
                while (j < chars.length) {
                    sb.append(chars[j]);
                    int mid = j + step - 2 * i;
                    if (mid < chars.length) {
                        sb.append(chars[mid]);
                    }
                    j += step;
                }
            }
        }
        return sb.toString();
    }
}

99.98%

答案

class Solution {
    public String convert(String s, int numRows) {

        if (numRows == 1) return s;

        StringBuilder ret = new StringBuilder();
        int n = s.length();
        int cycleLen = 2 * numRows - 2;

        for (int i = 0; i < numRows; i++) {
            for (int j = 0; j + i < n; j += cycleLen) {
                ret.append(s.charAt(j + i));
                if (i != 0 && i != numRows - 1 && j + cycleLen - i < n)
                    ret.append(s.charAt(j + cycleLen - i));
            }
        }
        return ret.toString();
    }
}
tags: LeetCode