Given an encoded string, return its decoded string.
The encoding rule is: k[encoded_string]
, where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a
or 2[4]
.
Examples:
s = "3[a]2[bc]", return "aaabcbc". s = "3[a2[c]]", return "accaccacc". s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
思路:因为存在嵌套的正括号,因此可采用栈数据结构stack< pair<int, string> >,first保存[]里字符串计数值,second记录[]左侧的字符串。
class Solution {
public:
string decodeString(string s) {
string res; //当前 ] 范围的字符串
//first记录[]里的个数,second记录[左侧的字符串
stack<pair<int, string>> stk;
int count=0;
for(auto c : s){
if(isdigit(c)){
count = count*10+ (c - '0');
}else if(c == '['){
stk.push({count,res});
res ="";
count =0;
}else if(c == ']'){
auto p = stk.top();
stk.pop();
string tmp = res;
for(int i=1; i< p.first; i++){
res += tmp;
}
res = p.second + res;
}else{
res += c;
}
}
return res;
}
};