LeetCode394(Decode String).

1.題目描述, examples:
s = “3[a]2[bc]”, return “aaabcbc”.
s = “3[a2[c]]”, return “accaccacc”.
s = “2[abc]3[cd]ef”, return “abcabccdcdcdef”.
解析 s.

2.代碼與描述(Java):

class Solution {
    public String decodeString(String s) {
        //用來獲取需要倍乘的次數
        Deque<Integer> times = new ArrayDeque<>();

        //用來構造結果
        Deque<StringBuilder> sbDeque = new ArrayDeque<>();

        //首先添加空String, 防止在沒有'[', ']'時候 pop 字符時會有 NoElement的異常。
        sbDeque.push(new StringBuilder(""));

        //獲取臨時的 multiplier
        int len = s.length();
        int multiplier = 0;
        for(int i = 0; i < len; i++){
            char tempChar = s.charAt(i);
            if(Character.isDigit(tempChar)){
                multiplier = multiplier*10 + Character.getNumericValue(tempChar);
            }else if(tempChar == '['){
                times.push(multiplier);
                multiplier = 0;
                sbDeque.push(new StringBuilder(""));
            }else if(tempChar == ']'){
                StringBuilder ss = new StringBuilder("");
                String tempString = sbDeque.pop().toString();
                int multip = times.pop();
                //這裏面不能寫 for(int j = 0; j < times.pop(); j++)否則會一直 times.pop()
                for(int j = 0; j < multip; j++){
                    ss.append(tempString);
                }
                sbDeque.push(sbDeque.pop().append(ss));
            }else{
                sbDeque.push(sbDeque.pop().append(tempChar));
            }
        }
        return sbDeque.pop().toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章