LeetCode 394 Decode String 题解

题意简述:给定一个解码规则k[encoded_string] -> encoded_string重复k次,以及一个根据此规则编码的字符串,求出解码后的字符串。
输入:编码的字符串s
输出:解码后的字符串
示例:字符串“3[a2[c]]”将被解码为“accaccacc”,3[a2[c]]=3[acc]=accaccacc


题解:
涉及到括号匹配和嵌套,因而采用DFS进行求解。
设置一个int记录当前处理的字符在字符串的下标cur,记在当前dfs函数中用来存放结果的字符串res。考虑当前处理的字符,只有4种可能:

  1. 当前字符是字母:直接在res末尾加入该字符,转到下一个字符。
  2. 当前字符是数字:设一个int记录应该重复的次数rep,因为重复的次数不一定只有一位数,所以需要把整个代表数的字符串找出来,cur一直增加直到遇到左方括号,然后将字符串计算转化为对应的数,例如“345”应该要算出345。
  3. 当前字符是左方括号:递归调用dfs函数,将返回的字符串重复rep次插入到res的末尾。
  4. 当前字符是右方括号:表示当前的dfs处理已完成,立刻返回res到上层的dfs函数。
    当然如果已经到达字符串的末尾,也会返回res。

代码实现如下:

class Solution {
private:
    int curind;
    string mystr;

    string dfs() {
        string res;

        while(curind < mystr.size()) {
            if(isalpha(mystr[curind])) {
                res.push_back(mystr[curind]);
                curind++;
            }

            if(isdigit(mystr[curind])) {
                int rep = 0;
                while(isdigit(mystr[curind])) {
                    rep = rep * 10 + (mystr[curind] - '0');
                    curind++;
                }

                curind++;
                string temp = dfs();
                for(int i = 0;i < rep;i++) res += temp;
            }

            if(mystr[curind] == ']') {
                curind++;
                return res;
            }
        }

        return res;
    }
public:
    string decodeString(string s) {
        curind = 0;
        mystr = s;
        return dfs();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值