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;
        }
    }
  • 相关阅读:
    无法识别的属性“targetFramework”。请注意属性名称区分大写和小写。错误解决的方法
    OpenGL 4 : 一个漂亮的心 For you, My Love
    request.getParameterValues与request.getParameter的差别
    Mac下搭建quick cocos2d-x编译环境
    【Github教程】史上最全github用法:github入门到精通
    OSI七层模型具体解释
    Android Service 服务(一)—— Service
    几种更新(Update语句)查询的方法
    epoll使用具体解释(精髓)
    SSL连接建立过程分析(1)
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9660211.html
Copyright © 2011-2022 走看看