参考:
https://leetcode.com/problems/decode-string/discuss/87651/C%2B%2B-simple-and-clear-solution
两个栈做的
class Solution {
public:
string decodeString(string s) {
stack<string> chars;
stack<int> nums;
string res;
int num = 0;
for(char c : s) {
if(isdigit(c)) { //找字符串中连续出现的数字并组成一个数,如 234(保存的是[之后的数字)
num = num*10 + (c-'0');
}
else if(isalpha(c)) { //将连续出现的字符组成字符串,保存的是[之后的字符串
res.push_back(c);
}
else if(c == '[') { //遇到'['就将之前字符串和数字分别入栈
chars.push(res);
nums.push(num);
res = "";
num = 0;
}
else if(c == ']') { //遇到']'就将数字和字符分别出栈一个并和当前字符组合一下
string tmp = res;
for(int i = 0; i < nums.top()-1; ++i) {
res += tmp;
}
res = chars.top() + res;
chars.pop(); nums.pop();
}
}
return res;
}
};
参考:https://leetcode.com/problems/decode-string/discuss/87544/Clean-C%2B%2B-Recursive-Solution-with-Explanation
递归方法做的:(其实没完全明白)
helper返回s[pos:]的解码。当遇到 ‘[’ 时,求之后的字符串解码,并重复当前数字次。当遇到 ’ ]’ 时,返回当前求得的字符串
class Solution {
public:
string decodeString(string s) {
int pos = 0;
return helper(pos, s);
}
string helper(int& pos, string s) {
int num=0;
string word = "";
for(;pos<s.size(); pos++) {
char cur = s[pos];
if(cur == '[') {
string curStr = helper(++pos, s);
for(;num>0;num--) word += curStr;
} else if (cur >= '0' && cur <='9') {
num = num*10 + cur - '0';
} else if (cur == ']') {
return word;
} else { // Normal characters
word += cur;
}
}
return word;
}
};