6. Z-transform

Simple simulation.

Use cur to record the current array location, and then cur++ each time if it increments downward, and reverse if it goes to the bottom. In the same way, when it’s up, it’s cur–, and when it’s up, it’s reverse.

The interesting point is how refactoring can simplify code while improving readability.

    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        StringBuilder[] builders = new StringBuilder[numRows];
        for (int i = 0; i < builders.length; i++) builders[i] = new StringBuilder();
        boolean down = false;
        int cur = 0;
        for (int i = 0; i < s.length(); i++) {
            builders[cur].append(s.charAt(i));
            if (i == 0 || i == numRows - 1) down = ! down; cur += down ?1 : -1;
        }
        StringBuilder builder = new StringBuilder();
        for (StringBuilder i : builders) builder.append(i);
        return builder.toString();
    }
Copy the code