394. Decode String

这道题目要实现的是字符串按照输入的格式进行解码,有点类似RLE算法,但是更复杂一点,因为这里有嵌套的解码,主要做法如下:
1、利用stack的先入后出性,设置countstack和resstack分别存储数字和字符;
2、当遇见‘【’时候,先把res放入resstack中,再reset为“”,来存储下次的字符
3、当遇见‘】’时候,先把resstack中pop,再加上下次要重复的字符(pop countstack 数字作为重复次数)。
代码如下:

public static String decodeString(String s) {
        String res="";
        Stack<Integer> countStack=new Stack<>();
        Stack<String> resStack=new Stack<>();
        int index=0;
        while (index<s.length()) {
            int count=0;
            if (Character.isDigit(s.charAt(index))) {
                while (Character.isDigit(s.charAt(index))) {
                    count=10*count+(s.charAt(index)-'0');   
                    index++;
                }
                countStack.push(count);
            }
            else if (s.charAt(index)=='[') {
                resStack.push(res);
                res="";
                index++;
            }
            else if (s.charAt(index)==']') {
                StringBuffer sb=new StringBuffer(resStack.pop());
                int num=countStack.pop();
                for (int i = 0; i < num; i++) {
                    sb.append(res);
                }
                res=sb.toString();
                index++;
            }
            else {
                res +=s.charAt(index);
                index++;
            }
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值