leetcode_394
Given an encoded string, return its decoded string.
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".Solutions
class Solution {
public:
string decodeString(string s) {
stack<pair<string, int>> lasts;
string cur_str = "";
int num = 0;
for (auto & c : s) {
// number
if (c < 'A')
num = num * 10 + (c - '0');
// characters
else if (c > ']' || c < '[')
cur_str.push_back(c);
else if (c == '[') {
lasts.push(make_pair(move(cur_str), num));
num = 0;
cur_str = "";
}
else {
auto left = lasts.top(); lasts.pop();
string & last_str = left.first;
for (int i = 0; i < left.second; i++)
last_str += cur_str;
cur_str = last_str;
num = 0;
}
}
return cur_str;
}
};Last updated