LeetCode解题报告 394. Decode String [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".

解题思路

题目的show tags 指出是dfs和stack相关,因此考虑用栈来实现。

可以看到字符串中字符出现的顺序一定是:数字--> [ --> 字母 --> ] ,以这四个为一组。建立两个栈,一个栈a用来存储这一组中的这一个数字,表明重复的次数。另一个栈b用来存储之前已经解码好的字符串(仍然以这样的四个为一组解码好的)。用 [ 和 ] 标识进栈和出栈。每次在遇到 [ 之后,就让数字(count来标识)进栈a,进栈以后立即让count归0,为了记录下一个数字。再让已经解码好的result字符串进栈,进栈以后result重置为空,为了存储接下来会遇到的字母(四个为一组到了第三个)。最后在遇到 ] 之后,对result重复栈a的数字的n-1次(已经有一次), 将之前栈b的字符串和result加起来为新的reslut就是这四个为一组解码好的加上之前已经解码好的字符串。将栈a,栈b出栈,也就是变为空栈。

最后不断这样重复,返回result。


复杂度分析
时间复杂度为O(n*n)

代码如下:
class Solution {
public:
    string decodeString(string s) {
        stack<int>numbers;
        stack<string>chars;
        int count=0;
        string result="";
        
        for (int i=0; i<s.size(); i++) {
            if (isdigit(s[i])) {
                count=count*10+s[i]-'0';
            }

            else if (s[i]=='[') {
                chars.push(result);
                numbers.push(count);
                result="";
                count=0;
                
            }
            
            else if (isalpha(s[i])) {
                result.push_back(s[i]);
            }
            
            else if (s[i]==']'){
                string temp=result;
                for (int j=0; j<numbers.top()-1; j++) {
                    result=result+temp;
                }
                result=chars.top()+result;
                chars.pop();
                numbers.pop();
                
            }
        }
        
        return result;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值