LeetCode 394. Decode String - Java - Stack

題目鏈接:394. 字符串解碼

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].

Examples:

s = “3[a]2[bc]”, return “aaabcbc”.
s = “3[a2[c]]”, return “accaccacc”.
s = “2[abc]3[cd]ef”, return “abcabccdcdcdef”.

題解

字符是左括號,將重複次數和此次重複之前的字符串添加到棧頂
字符是右括號,取出棧頂數據,此數據是當前括號內的字符串重複次數
字符是數字,將數字添加到num中
字符是字母,將字母添加到當前字符串中

時間複雜度爲 O(n)O(n)
空間複雜度爲 O(n)O(n)

官方推薦使用Deque接口和ArrayDeque類代替Stack類。方法對應關係爲

Deque Stack
addFirst push
removeFirst pop

Java代碼

/**
 * 時間複雜度爲O(n),只需要一次遍歷字符串即可
 * 空間複雜度爲O(n),括號越多棧越深
 * <p>創建日期:2020-05-28 16:05:56</p>
 *
 * @author PengHao
 */
class Solution {
    public String decodeString(String s) {
        StringBuilder result = new StringBuilder();
        // 棧,保存重複次數
        Deque<Integer> integers = new ArrayDeque<>();
        // 棧,此次重複串之前的字符串
        Deque<StringBuilder> builders = new ArrayDeque<>();
        int num = 0;
        // 遍歷字符串s,時間複雜度爲O(n)
        for (char ch : s.toCharArray()) {
            if (ch == '[') {
                // ch是左括號,將重複次數和此次之前的字符串入棧
                integers.addFirst(num);
                builders.addFirst(result);
                // 重置次數和結果字符串
                num = 0;
                result = new StringBuilder();
            } else if (ch == ']') {
                // ch是右括號,將該括號中的字符串(result)重複pop次,
                // pop是該括號前面的數據(即棧頂數據)
                StringBuilder temp = new StringBuilder();
                int pop = integers.removeFirst();
                for (int i = 0; i < pop; i++) {
                    temp.append(result);
                }
                // 將此次重複串前面的字符串從棧頂取出並加上此次重複的字符串
                result = builders.removeFirst().append(temp);
            } else if (Character.isDigit(ch)) {
                // ch是數字
                num = num * 10 + Character.digit(ch, 10);
            } else {
                // ch是字母
                result.append(ch);
            }
        }
        return result.toString();
    }
}

參考

1、字符串解碼(輔助棧法 / 遞歸法,清晰圖解) - Krahets

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章