394. Decode String

给定一个编码字符串,返回它的解码字符串。

编码规则是:k[encoded_string],其中方括号内的encoded_string重复k次,k是正整数。

您可以假设输入字符串始终有效; 没有多余的空白区域,方括号格式正确等。

此外,您可以假设原始数据不包含任何数字,并且该数字仅用于那些重复数字k。例如,不会有像3a或那样的输入2[4]。

例子:

s =“3 [a] 2 [bc]”,返回“aaabcbc”。
s =“3 [a2 [c]]”,返回“accaccacc”。
s =“2 [abc] 3 [cd] ef”,返回“abcabccdcdcdef”。

解决方法1:堆栈

  • 如果遇到数字num,代表要重复接下来的 [ ] 的内容num次数,把它存入operate堆栈中
  • 如果遇到 ‘ [ ’ ,那么需要把之前已经读取的内容存到堆栈strStack中,并且用result来记录接下来要重复的内容
  • 如果遇到字母,就把它存入当前结果中
  • 如果遇到 ‘ ] ’ ,那么代表要把当前result中的内容重复operate.pop()次,重复后与之前已经读取的最相近的strStack中内容结合起来
class Solution {
    public String decodeString(String s) {
        
        if(s == null || s.length() == 0) return "";
        int len = s.length();
        Stack<Integer> operate = new Stack<Integer>();
        Stack<String> strStack = new Stack<String>();
        int i = 0;
        String result = "";
      
        l:while(i < len)
        {
            int num =0;
            while(s.charAt(i) <= '9' && s.charAt(i) >= '0')
            {
                num = num*10 + s.charAt(i)-'0';
                i++;
            }
            if(num>0)operate.add(num);
            
            if(s.charAt(i) == '[')
            {
                strStack.push(result);
                result = "";
                i++;
            }
            while(s.charAt(i) <= 'z' && s.charAt(i) >= 'a')
            {
                result += s.charAt(i++);
                if(i == s.length()) break l;
            }
           
            if(s.charAt(i) == ']')
            {
                String sb = strStack.pop();
                int time = operate.pop();
                for(int j = 0;j < time;j++)
                    sb = sb + result;
                result = sb;
                i++;
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值