zoukankan      html  css  js  c++  java
  • leetcode394

    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;
        }
    }
  • 相关阅读:
    2019/09/26,经济和科技
    失败的总和
    2019/11/05,现代人的焦虑
    2019/09/16,回忆和希望
    2019/09/13,捷径
    演讲手势
    因果谬论和基于数据的另一种说法
    文本框输入事件:onchange 、onblur 、onkeyup 、oninput
    开关按钮切换
    全选,反选,全不选
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9660211.html
Copyright © 2011-2022 走看看