leetcode菜狗入门 | 394. 字符串解码

字符串解码

题目描述

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

编码规则为: 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".

解题思路

建两个栈,一个数字栈一个字符栈,数字栈存放倍数。字符栈如果遇到 ‘]’,就出栈直至遇到 ‘[’ ,数字栈栈顶出栈,把出栈的字符串按照倍数进行变换,如果字符栈非空就在放入字符栈,否则拼接在 ans 后,如果字符栈与数字栈全为空,就将当前字符直接拼在 ans后

代码

class Solution {
public:
    string decodeString(string s) {
        stack<int> count;
        stack<char> str;
        string ans = "";
        if(s.length() == 0) return ans;
        int i = 0;
        int num = -1;
        while(i < s.length()){
            while(s[i] >= '0' && s[i] <= '9' && i < s.length()){
                if(num == -1)
                    num = s[i] - '0';
                else
                    num = num*10 + (s[i]-'0');
                i++;
            }
            if(num != -1){
                count.push(num);
                num = -1;
            }
            if(count.empty() && str.empty()){
                ans.push_back(s[i]);
                i++;
                continue;
            }
            if(s[i] != ']'){
                str.push(s[i]);
                i++;
            }
            else{
                string temp = "";
                while(str.top() != '['){
                    temp.push_back(str.top());
                    str.pop();
                }
                str.pop();
                reverse(temp.begin(), temp.end());
                int beishu = count.top();
                //cout<<beishu<<endl;
                count.pop();
                string cur = temp;
                for(int j = 1; j <beishu; j++){
                    temp += cur;
                }
                if(str.empty())
                    ans += temp;
                else{
                    for(int j = 0; j < temp.length(); j++){
                        str.push(temp[j]);
                    }
                }
                i++;
            }
        }
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值