394. Decode String

總結:

  1. 不可在for loop中計算, 一定要input一個fixed value
    錯誤例子
    e.g. for (int i=0; i<count_stack.pop(); i++){
    sb.append(res);

思路: 用兩個stack分別存入要乘的數字和英文
int index 維持string下標
遇到 左中括號 [ 時將 cum_num 和 res 壓棧
遇到 右中括號 ] 時將 count_stack中取出item, 乘以現時的res, 再append res_stack中取出的已計算res

留意中括號前的數字可能是兩位數

別人代碼:


public String decodeString(String s) {
    String res = "";
    // 记录'['之前的数字
    Stack<Integer> countStack = new Stack<>();
    // 记录'['之前的运算结果
    Stack<String> resStack = new Stack<>();
    int idx = 0;
    int curNum = 0;
    while (idx < s.length())
 
    {
        char ch = s.charAt(idx);
        if (Character.isDigit(ch)) {
            while (Character.isDigit(s.charAt(idx)))
                curNum = 10 * curNum 
                    + (s.charAt(idx++) - '0');
        } else if (ch == '[') {
            resStack.push(res);
            res = "";// 注意
            // 此push可以放在上面的while循环中
            countStack.push(curNum);
            curNum = 0;// 注意
            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;

————————————————
版权声明:本文为CSDN博主「mine_song」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/mine_song/article/details/71036245
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容