leetcode394 - Decode String - medium

Given an encoded string, return it's 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".

Stack。模拟题
变量:stackNum, stackStr, String result
Result的str得一直暴露在外面,因为题目example里可以看到可以省去k ==1时的数字和括号,为了把这些字母也能append上去,就把result一直暴露在外面随时可以加。
General case关键在[和]上,大体印象是,
1.看到[,已经可以确定前面的是写死的了,把目前暂时得到的前面的result先放stack里去存一下,然后记得给result清空”"。
2.看到],知道和]匹配的[中间包住的这部分也可以写死了。把上一个压近stack的前面定死result拿出来,再捣鼓捣鼓把最近收集的局部result和pop出的count倍乘一下append上去。
3.看到数字,while循环一下把数字都提出来,转换后压入count的stack。
4.看到字母,直接append到result上。

实现:

class Solution {
    public String decodeString(String s) {
        String res = "";
        // 记录'['之前的数字
        Stack<Integer> countStack = new Stack<>();
        // 记录'['之前的运算结果
        Stack<String> resStack = new Stack<>();
        int idx = 0;

        while (idx < s.length()) {
            char ch = s.charAt(idx);
            if (Character.isDigit(ch)) {
                int curNum = 0;
                while (Character.isDigit(s.charAt(idx))) {
                    curNum = 10 * curNum + (s.charAt(idx++) - '0');
                }
                countStack.push(curNum);
            } else if (ch == '[') {
                resStack.push(res);
                res = "";
                idx++;
                // 取出计算结果,和数字
            } else if (ch == ']') {
                StringBuilder temp = new StringBuilder(resStack.pop());
                int repeatTimes = countStack.pop();
                for (int i = 0; i < repeatTimes; i++) {
                    temp.append(res);
                }
                res = temp.toString();
                idx++;
                // 字母
            } else {
                res += s.charAt(idx++);
            }
        }
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/jasminemzy/p/9660211.html
今日推荐