394. 字符串解码
class Solution {
public:
string decodeString(string s) {
string ans = "";
int num = 0;
stack<pair<string, int> > S;
for(auto ch : s) {
if(ch >= '0' && ch <= '9') num = num * 10 + ch - '0';
else if(ch == '[') {
S.push({ans, num});
ans = "";
num = 0;
}
else if(ch == ']') {
string last_str = "";
int last_num = 0;
std::tie(last_str, last_num) = S.top();
S.pop();
while(last_num--) last_str += ans;
ans = last_str;
}
else ans += ch;
}
return ans;
}
};
class Solution {
public:
string decodeString(string s) {
stack<int> S_num;
stack<char> S_ch;
int num = 0;
for(auto ch : s) {
if(ch >= '0' && ch <= '9') num = num * 10 + ch - '0';
else {
if(ch == '[' && num != 0) S_num.push(num);
if(ch == ']') {
string temp = "";
while(!S_ch.empty() && S_ch.top() != '[') {
temp = S_ch.top() + temp;
S_ch.pop();
}
if(!S_ch.empty() && S_ch.top() == '[') S_ch.pop();
num = S_num.top();
S_num.pop();
while(num--) for(auto t : temp) S_ch.push(t);
}
else S_ch.push(ch);
num = 0;
}
}
string ans = "";
for( ; !S_ch.empty(); S_ch.pop()) ans = S_ch.top() + ans;
return ans;
}
};