1. 程式人生 > >佇列&棧//字串解碼

佇列&棧//字串解碼

給定一個經過編碼的字串,返回它解碼後的字串。

編碼規則為: 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".

 

class Solution {
public:
    string decodeString(string s) {
        int i = 0;
        return decode(s,i);
    }
    string decode(string s,int &i){
        string res = "";
        int n = s.size();
        while(i < n&&s[i] != ']'){
            if(s[i]<'0'||s[i]>'9'){
                res+=s[i++];
            }else{
                int cnt = 0;
                while(i<n&&s[i]>='0'&&s[i]<='9'){
                    cnt = cnt*10+s[i++]-'0';
                }
                i++;
                string t = decode(s,i);
                i++;
                while(cnt-->0){
                    res+=t;
                }
            }
        }
        return res;
    }
};
class Solution {
public:
    string decodeString(string s) {
        string res = "", t = "";
        stack<int> s_num;
        stack<string> s_str;
        int cnt = 0;
        for(int i = 0; i < s.size(); i++){
            if(s[i] >= '0' && s[i] <= '9'){
                cnt = 10 * cnt + s[i] - '0';
            }else if(s[i] == '['){
                s_num.push(cnt);
                s_str.push(t);
                cnt = 0;
                t.clear();
            }else if(s[i] == ']'){
                int k = s_num.top();
                s_num.pop();
                for(int j = 0; j < k; j++)
                    s_str.top()+=t;
                t = s_str.top();
                s_str.pop();
            }else{
                t += s[i];
            }
        }
        return s_str.empty()?t:s_str.top();
    }
};