leetcode: 6. ZigZag Conversion

Difficulty

Medium

Description

/**
 * The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
 * P   A   H   N
 * A P L S I I G
 * Y   I   R
 * And then read line by line: "PAHNAPLSIIGYIR"
 * 
 * Example 1:
 * Input: s = "PAYPALISHIRING", numRows = 3
 * Output: "PAHNAPLSIIGYIR"
 */

Solution

Time Complexity: O(n), where n == len(s)
Space Complexity: O(n)

class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        
        List<StringBuilder> rows = new ArrayList<>();
        //Math.min(numRows, s.length())为非空行数
        for (int i = 0; i < Math.min(numRows, s.length()); i++) {
            rows.add(new StringBuilder());
        }
        int curRow = 0; //当前所在行
        boolean goDown = false;  //当前字母走向
        
        for (char c: s.toCharArray()) {
            rows.get(curRow).append(c);
            if (curRow == 0 || curRow + 1 == numRows)  //第一行和最后一行时改变走向
                goDown = !goDown;
            curRow += goDown? 1 : -1;
        }
        StringBuilder ret = new StringBuilder();
        for (StringBuilder row: rows)
            ret.append(row);
        return ret.toString();
    }   
}

猜你喜欢

转载自blog.csdn.net/baidu_25104885/article/details/85239397
今日推荐