394. 字符串解码

递归

class Solution {
public:
    string dfs(string s, int &start){
        string res;
        int multi_num=0;
        for(int i=start;i<s.length();){
            if(isdigit(s[i])){
                multi_num = multi_num*10+s[i]-'0';
                i++;
            }else if(s[i]=='['){
                i++;
                string multi_string = dfs(s, i);
                for(int j=0; j<multi_num; ++j) 
                    res+=multi_string;
                multi_num = 0;
            }else if (s[i]==']'){
                start = i+1;
                return res;
            }else{
                res+=s[i];
                i++;
            }
        }
        return res;
    }
    string decodeString(string s) {
        int start = 0;
        return dfs(s,start);
    }
};

用栈

class Solution {
public:
    string decodeString(string s) {
        stack<int>multi;
        stack<string>preString;
        string res;
        int multi_num = 0;
        for(auto c:s){
            if(isdigit(c)){
                multi_num = multi_num * 10 + c-'0'; 
            }else if(c=='['){
                multi.push(multi_num);
                preString.push(res); //pre res是两个 [ 之间的字母串
                multi_num=0;
                res="";
            }else if(c==']'){
                string multiString;
                for(int i=0;i<multi.top();++i)
                    multiString += res;
                multi.pop();
                res =  preString.top() + multiString;
                preString.pop();
            }else{
                res+=c;
            }
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode,算法,数据结构)