Leetcode 394 Decode String

DecodeString 解析字符串

题目描述

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

示例

s = “3[a]2[bc]”, return “aaabcbc”.
s = “3[a2[c]]”, return “accaccacc”.
s = “2[abc]3[cd]ef”, return “abcabccdcdcdef”.

题目解析

给一个编号的字符串,返回他的解码字符串。

从题中我们可以看出,当碰到括号时。需要将括号内的字符串根据括号前的数字来复制字符串。我们可以把题目解析成这样,没遇到一个括号就计算一次字符串,也就是解码一次字符串,然后将其与前面的字符串结合进行下一次解码。由于每次都要与前面的字符串结合,这里必须记录一个状态下的前面字符串。因此我们可以用栈的方式来记录栈的状态以及字符串。由题目知道,我们需要记录的由两个状态,一个是字符串,一个是需要重复的次数。因此设计了两个栈来记录中间状态。
得到如下代码。

代码解析

/**
     * @author AbrahamHan
     * @param s
     * @return res
     */

    public String decodeString(String s) {
        int len = s.length();
        //数字栈,记录每层数字大小
        LinkedList<Integer> numstack = new LinkedList<Integer>(); 
        //String栈,记录每层String
        LinkedList<String> strstack = new LinkedList<String>();
        String res = "",tmp="",str = "";
        Integer num = 0;
        for(int i = 0 ; i < len ; i++){

            char ch = s.charAt(i);
            if(ch == ']')
            {
                num = numstack.pop();
                //如果匹配到后括号,直接计算当前栈的字符串
                String tmpstr = "";
                for(int j = 0;j < num ;j++)
                    tmpstr = tmpstr + str;
                str = strstack.pop() +tmpstr;
                num = 0;
            }
            //如果匹配到左括号,将当前栈的数字和str压入栈
            else if(ch == '[')
            {
                numstack.push(num);
                strstack.push(str);
                str = "";
                num = 0;
            }
            //如果匹配到数字,计算数值大小
            else if(ch>='0' && ch <= '9')
            {
                num = num * 10 + (ch-'0');
            }
            //如果匹配到字符,计算字符串
            else
            {
                str = str +ch;
            }

        }
        return str;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值