Advertisement
leoanjos

Decode String (Non-forbidden Way)

May 21st, 2022
1,261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string decodeString(string s) {
  4.         stack<string> strings;
  5.         stack<int> multipliers;
  6.        
  7.         string ans = "";
  8.         for (int i = 0; i < (int) s.size(); i++) {
  9.             if (s[i] == '[') {
  10.                 strings.push("");
  11.             } else if (letter(s[i])) {
  12.                 if (strings.empty()) ans += s[i];
  13.                 else strings.top() += s[i];
  14.             } else if (digit(s[i])) {
  15.                 if (i == 0 || !digit(s[i - 1])) multipliers.push(s[i] - '0');
  16.                 else {
  17.                     multipliers.top() *= 10;
  18.                     multipliers.top() += s[i] - '0';
  19.                 }
  20.             } else {
  21.                 int multiplier = multipliers.top();
  22.                 multipliers.pop();
  23.                
  24.                 string str = strings.top();
  25.                 strings.pop();
  26.                
  27.                 while (multiplier--) {
  28.                     if (strings.empty()) ans += str;
  29.                     else strings.top() += str;
  30.                 }
  31.             }
  32.         }
  33.        
  34.         return ans;
  35.     }
  36.    
  37. private:
  38.     bool letter(char c) {
  39.         return c >= 'a' && c <= 'z';
  40.     }
  41.    
  42.     bool digit(char c) {
  43.         return c >= '0' && c <= '9';
  44.     }
  45. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement