·394.字符串解码

题目描述

在这里插入图片描述
注意 k 保证为正整数。你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

解题思路 ❤❤❤

  • 为什么用栈?
    • 括号内嵌套括号,需要从内向外生成与拼接字符串,这与栈的先入后出特性对应。
  • 辅助栈解法
    ① 遍历字符串 s 中每个字符 c;
    ② 当 c 为数字时,将数字字符转化为数字 multi,用于后续倍数计算;
    ③ 当 c 为字母时,在 res 尾部添加 c;
    ④ 当 c 为 [ 时,将当前 multi 和 res 入栈,并分别置空置 0:
    ⑤ 当 c 为 ] 时,stack 出栈,拼接字符串 res = last_res + cur_multi * res,其中:
    last_res是上个 [ 到当前 [ 的字符串,例如 “3[a2[c]]” 中的 a;
    cur_multi是当前 [ 到 ] 内字符串的重复倍数,例如 “3[a2[c]]” 中的 2。
    ⑥ 返回字符串 res。

JAVA思路(辅助栈)

class Solution {
    public String decodeString(String s) {
        int multi = 0;
        StringBuilder res = new StringBuilder();
        Stack<Integer> stack_multi = new Stack<>();
        Stack<String> stack_res = new Stack<>();
        for(Character c : s.toCharArray()) { // 注意这里的Character,以及toCharArray方法
            if(c >='0' && c<='9') 
                multi = multi*10 + Integer.parseInt(c+""); // +""作用是转换为字符串,也可以写成c-'0'
            else if(c == '['){
                stack_multi.push(multi);
                stack_res.push(res.toString()); // 变成string
                multi = 0;
                res = new StringBuilder();
            }
            else if(c ==']'){
                StringBuilder tmp = new StringBuilder();
                int num = stack_multi.pop();
                for(int i=0 ; i<num ; i++) tmp.append(res);
                res = new StringBuilder(stack_res.pop() + tmp); //注意是stack_res
            }
            else res.append(c);
        }
        return res.toString();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值