LeetCode #394 - Decode String -Medium

Problem

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.
For example, there won't be input like 3a or 2[4].

Example

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

Algorithm

整理一下题意:给定一个编码过的字符串,要求返回对应的解码字符串。编码规则是,k[s]表示[]中的字符串s要重复k次。假设k是正整数;输入有效,没有多余空格且方括号对应正确;方括号中只有字母,没有数字。

本题的难点在于需要考虑嵌套的情况。整理一下,对于每个字符串,如果是无嵌套的情况,遇到数字则以数字为倍数保存后续方括号中的内容。如果含嵌套,则嵌套的内容视为子问题递归求解。对于不涉及方括号的情况,此时给定字符串中出现普通的字符,这部分字符直接附加到结果串中。

在不同层次的递归中,指向的位置是顺序的,故维护一个共同的位置索引,可以通过引用参数“&”来实现。

特别注意[]前的数字不一定是个位数,需要进行简单的计算。

//DFS
class Solution {
public:
    string decodeString(string s) {
        if(s.size()==0) return "";
        int i=0;
        return dfs(s,i);
    }

    string dfs(string s, int& i){
        string ans;
        int count=0;
        while(i<s.size()){
            if(s[i]>='0'&&s[i]<='9'){
                count=(count*10+s[i]-'0');
                i++;
            }
            else if(s[i]=='['){
                i++;
                string t=dfs(s,i);
                for(int j=0;j<count;j++) ans+=t;
                count=0;
            }
            else if(s[i]==']'){
                i++;
                return ans;
            }
            else{
                ans+=s[i];
                i++;
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值