LeetCode-394-字符串解码

本文详细介绍了如何解决LeetCode第394题——字符串解码问题。通过使用两个栈分别存储数字和子串,逐一解析字符串,遇到'['和']'时进行相应操作,最终得到解码后的字符串。核心思路在于栈的应用和数字计算。

LeetCode-394-字符串解码

在这里插入图片描述

思路

使用2个栈分别存储“[“前的字符串和数字

  • ch[i]=数字:num=num*10+数字
  • ch[i]=字符:res+=字符;
  • ch[i]=’[’:num和res入栈,置0置空
  • ch[i]=’]’:出栈,计算字符串,次数=nums.pop(),str=strs.pop(),拼接str和res,res更新为str

代码

class Solution {
    public String decodeString(String s) {
        Stack<Integer> nums=new Stack<>();//存放"["前的数字
        Stack<StringBuilder> strs=new Stack<>();//存放"["前的字符串
        char[] ch=s.toCharArray();
        StringBuilder res=new StringBuilder("");//保存当前遍历到的字符串
        int num=0;
        for(int i=0;i<ch.length;i++){
            if(ch[i]>='0'&&ch[i]<='9')num=num*10+ch[i]-'0';//可能是多位数字因此必须num*10
            else if((ch[i]>='a'&&ch[i]<='z')||(ch[i]>='A'&&ch[i]<='Z')){
                res.append(ch[i]);//字符串拼接
            }
            else if(ch[i]=='['){
                //遇到"[",全部入栈,临时变量置0置空
                nums.push(num);
                num=0;
                strs.push(res);
                res=new StringBuilder("");
            }
            else{
                //遇到"]",栈顶出栈进行计算
                int times=nums.pop();//表示当前res的次数
                StringBuilder str=strs.pop();//表示[]前的字符串,用于拼接[]中的字符串
                for(int j=0;j<times;j++){
                    str.append(res);//拼接
                }
                res=new StringBuilder(str);//res更新为拼接后的字符串
            }
        }
        return res.toString();
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值