56.Decode String(解码字符串)

Level:

  Medium

题目描述:

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".
思路分析:

  设置两个栈,一个栈countstack保存方框内字符串的重复次数,一个栈resstack保存目前解码的字符串,用res记录结果,当遇到字符' ] '时,我们弹出countstack的栈顶元素reaptetime,然后将res重复reaptetime次,放入resstack栈中。

代码:
public class Solution{
    public String decodeString(String s){
        Stack<Integer>countstack=new Stack<>();
        Stack<String>resstack=new Stack<>();
        String res=""; //保存最终结果
        int i=0;
        while(i<s.length()){
            if(Character.isDigit(s.charAt(i))){ //计算重复次数
                int count=0;
                while(Character.isDigit(s.charAt(i))){
                    count=count*10+(s.charAt(i)-'0');
                    i++;
                }
                countstack.push(count);
            }else if(s.charAt(i)=='['){
                resstack.push(res); //将之前解码的字符串存放到栈中
                res="";  //重置res
                i++;
            }else if(s.charAt(i)==']'){
                int reaptetime=countstack.pop();
                StringBuilder temp=new StringBuilder();
                for(int j=0;j<reaptetime;j++){
                    temp.append(res);
                }
                res=resstack.pop()+temp.toString();//当前解码结果
                i++;
            }else{
                res=res+s.charAt(i);
                i++;
            }
        }
        return res;
    }
}

转载于:https://www.cnblogs.com/yjxyy/p/11089405.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值