394. 字符串解码

dfs:

class Solution {
public:
    string decodeString(string s) {
        int i=0;
        return dfs(s,i);
    }
    string dfs(string& s,int& i){//计算一对括号内的解码后字符串
        string tmp="";
        while(i<s.size()){
            if(s[i]==']'){//当前括号完毕
                ++i;
                return tmp;
            }
            else if(s[i]<='9' and s[i]>='0'){
                int j=i+1;
                while(j<s.size() and s[j]!='['){
                    ++j;
                }
                //j==s.size() 或者s[j]=='[',数字从i到j-1
                int num=stoi(s.substr(i,j-i));
                i=j+1;//跳过'['   j==s.size()也无所谓
                string t=dfs(s,i);
                for(int i=0;i<num;++i){
                    tmp+=t;
                }
                //括号中字符串累加到当前字符串尾部
            }
            else{//'a'~'z'  'A'~'Z' 直接加到尾部
                tmp+=s[i++];
            }
        }
        return tmp;
    }
};

栈:

class Solution {
public:
    string decodeString(string s) {
        stack<char> sta;
        int i=0;
        string res="",tmp,num;
        while(i<s.size()){
            if(s[i]==']'){
                while(sta.top()!='['){
                    tmp+=sta.top();
                    sta.pop();
                }
                reverse(tmp.begin(),tmp.end());
                sta.pop();//pop '['
                while(not sta.empty() and sta.top()<='9' and sta.top()>='0'){
                    num+=sta.top();
                    sta.pop();
                }
                reverse(num.begin(),num.end());
                int nnum=stoi(num);
                while(nnum){//把nnum个tmp压回栈里
                    for(auto& c:tmp){
                        sta.push(c);
                    }
                    --nnum;
                }
                tmp="",num="";//归零
            }
            else{//其他元素一律压入栈里
                sta.push(s[i]);
            }
            ++i;
        }
        while(not sta.empty()){
            res+=sta.top();
            sta.pop();
        }
        reverse(res.begin(),res.end());
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值