Skip to content

0394. Decode String

Given an encoded string, return its decoded string.

The encoding rule is: k[encoded_string], where the encoded_stringinside the square brackets is being repeated exactly k times. Note that kis guaranteed to be a positive integer.

You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.

Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won't be input like 3a or 2[4].

Example 1:

Input: s = "3[a]2[bc]"
Output: "aaabcbc"

Example 2:

Input: s = "3[a2[c]]"
Output: "accaccacc"

Example 3:

Input: s = "2[abc]3[cd]ef"
Output: "abcabccdcdcdef"

Example 4:

Input: s = "abc3[cd]xyz"
Output: "abccdcdcdxyz"

Analysis

There are two parts we need to take care of:

  1. repeated number: cnt
  2. string enclosed by '[]': t

So we need to ues two stacks to store the above two information: stack<int> times which store the current repeated number and stack<string> stk which store the current concatenated string.

  1. If we see a number, we append the digit to our current partial formed number.
  2. If we see '[', we can stop tracking our number string (convert it to integer and push it to the top of timestack), and also we need to start push string to stk.
  3. If we see ']', we should start "duplicating" times.top() \times t and push that to our stk.

  4. Time; O(n)

  5. Space: O(n)

Code

class Solution {
public:
  string decodeString(string s) {
    stack<int> times;
    stack<string> stk;
    int cnt = 0;
    string t = "";
    for (char c : s) {
      if (c <= '9' && c >= '0') {
        cnt = cnt * 10 + c - '0';
      } else if (c == '[') {
        times.push(cnt);
        stk.push(t);
        cnt = 0;
        t = "";
      } else if (c == ']') {
        int time = times.top();
        times.pop();
        for (int i = 0; i < time; ++i) {
          stk.top() += t;
        }
        t = stk.top();
        stk.pop();
      } else {
        t += c;
      }
    }
    return stk.empty() ? t : stk.top();
  }
};

Last update: April 1, 2022