LeetCode 394. Decode String

本文介绍了一种解码重复子串的算法,通过使用计数栈和字符串栈,能够高效地解析并还原由k[encoded_string]形式编码的字符串。文章详细解释了算法的工作流程,并提供了具体实例说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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".

务必代入 s = "3[a2[c]]", return "accaccacc". 这个例子观察countStack,StringStack,res的变化过程

class Solution {
    
    public String decodeString(String s) {
        Stack<Integer> countStack = new Stack<>();
        Stack<String> StringStack = new Stack<>();
        
        int i = 0;
        int count = 0;
        String res = new String();
        while(i<s.length()){
            
            //数字情形单独处理,因为数字可能是32,132等多位数字
            while(s.charAt(i)>='0'&&s.charAt(i)<='9'){
                count = count*10 + s.charAt(i)-'0';
                i++;
            }
            if(count!=0){
                countStack.push(count);
                count = 0;
            }
            
            if(s.charAt(i)=='['){//一旦遇到左括号,就把此时的res放入StringStack中,然后用res记录括号中的字符串
                StringStack.push(res);
                res = new String();
                i++;
            }
            else if(s.charAt(i)==']'){//一旦遇到右括号,就将res恢复为此时应有的
                String prev = StringStack.pop();
                int n = countStack.pop();
                for(int k = 0;k<n;k++){
                    prev += res;
                }
                res = prev;
                i++;
            }
            else{//可能是左括号之内的小写字母或者是不加括号的小写字母
                res += s.charAt(i);
                i++;
            }
            
        }
        
        
        return res;
        
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值