Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- string decodeString(string s) {
- stack<string> strings;
- stack<int> multipliers;
- string ans = "";
- for (int i = 0; i < (int) s.size(); i++) {
- if (s[i] == '[') {
- strings.push("");
- } else if (letter(s[i])) {
- if (strings.empty()) ans += s[i];
- else strings.top() += s[i];
- } else if (digit(s[i])) {
- if (i == 0 || !digit(s[i - 1])) multipliers.push(s[i] - '0');
- else {
- multipliers.top() *= 10;
- multipliers.top() += s[i] - '0';
- }
- } else {
- int multiplier = multipliers.top();
- multipliers.pop();
- string str = strings.top();
- strings.pop();
- while (multiplier--) {
- if (strings.empty()) ans += str;
- else strings.top() += str;
- }
- }
- }
- return ans;
- }
- private:
- bool letter(char c) {
- return c >= 'a' && c <= 'z';
- }
- bool digit(char c) {
- return c >= '0' && c <= '9';
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement