标签: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; } };
标签:code tco 解码 表示 额外 tac 版本 nbsp etc
原文地址:https://www.cnblogs.com/hlk09/p/9732950.html