標籤: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 字串解碼