题目

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"

(直译过来是之字形,其实就是 N 啊...)

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

输入输出例子

分析

参数 numRows 就是行数,也就是整个字符串要拆分成指定行数,以 3 行为例,上一段的输入字符串每个字母所对应的行数如下(行数从 0 开始)

原字符串:P A Y P A L I S H I R I N G
输出行数:0 1 2 1 0 1 2 1 0 1 2 1 0 1

可以看出字符串从左到右,就是按照 0121 的规律在做行变换。所以,代码思路就是,循环字符串,将指定位置的字符串放入对应的行中。

代码

public String convert(String s, int numRows) {
        if (numRows == 1) return s;

        List<StringBuilder> rows = new ArrayList<>();
        for (int i = 0; i < Math.min(numRows, s.length()); i++)
            rows.add(new StringBuilder());

        int curRow = 0;
        boolean goingDown = false;

        for (char c : s.toCharArray()) {
            rows.get(curRow).append(c);
            if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
            curRow += goingDown ? 1 : -1;
            //System.out.println(curRow);
        }

        StringBuilder ret = new StringBuilder();
        for (StringBuilder row : rows) ret.append(row);
        return ret.toString();
    }

    @Test
    public void test(){
        System.out.println(convert("PAYPALISHIRING", 3));
        System.out.println(convert("PAYPALISHIRING", 4));
    }

输出

PAHNAPLSIIGYIR
PINALSIGYAHRPI


原文:https://leetcode.com/problems/zigzag-conversion/

end.