LeetCode 394 字串解碼

來源:互聯網
上載者:User

標籤:code   tco   解碼   表示   額外   tac   版本   nbsp   etc   

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

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

首先,雖然這個題是在Stack Tag下的,但是使用遞迴仍是比較簡單的做飯。在我提交的版本中,因為過多使用了substr,導致執行時間比較長。參考了時間第一的做法:

class Solution {public:    string decodeString(string s) {        int i=0;        return getstring(s,i);    }private:    string getstring(string s,int&i)    {        string res="";        while(i<s.length()&&s[i]!=‘]‘)        {            if(!isdigit(s[i]))                res+=s[i++];            else            {                   string num="";                while(isdigit(s[i])&&i<s.length())                    num+=s[i++];                i++;                int times=stoi(num);                string sub=getstring(s,i);                for(int k=0;k<times;k++)                    res+=sub;                     i++;            }                    }        return res;    }};

當然也是可以用棧解決的,只是本人不會。用到了輔助棧。參考網上的做法:

class Solution {public:    string decodeString(string s) {        string t;        stack<int> num;        stack<string> str;        int cnt = 0;        for(int i = 0; i < s.size(); i++) {            if(isdigit(s[i])) {                cnt = 10 * cnt + s[i] - ‘0‘;            } else if(s[i] == ‘[‘) {                num.push(cnt);                str.push(t);                cnt = 0;                t.clear();            } else if(s[i] == ‘]‘) {                for(int j = 0; j < num.top(); j++) {                    str.top() += t;                }                t = str.top();                num.pop();                str.pop();            } else {                t += s[i];            }        }        return t;    }};

 

LeetCode 394 字串解碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.