<AI/>
enru
All posts

Decode string

LeetCode 394: Decode a string encoded with the k[encoded_string] rule, including nested blocks, using recursion.

Difficulty
Medium
Published
Topics
#string#recursion
Open on LeetCode

Problem Description

You are given an encoded string; return its decoded version.

The encoding rule is k[encoded_string], meaning the string inside the square brackets must be repeated exactly k times. Note that k is guaranteed to be a positive integer.

The input string is always guaranteed to be valid: there are no extra spaces and the square brackets are well-formed. Furthermore, the digits in the string are only used for the repeat numbers k. For example, there won't be input like 3a or 2[4].

Note that encoded strings can be nested inside each other.

Constraints

  • The input string length is in the range from 1 to 30
  • The input string consists only of lowercase English letters, digits and square brackets
  • The input string is always valid
  • k is in the range from 1 to 300
  • The length of the resulting string does not exceed 105

Examples

Input: "3[a]2[bc]"

Answer: "aaabcbc"

Solution

This problem can be solved recursively with the following algorithm.

  1. Create an empty result string that accumulates the decoded output.
  2. Iterate over the string character by character and check the following:
    • If the current character is a letter (from 'a' to 'z'), append it to the result res and move on to the next character.
    • If it's a digit, it marks the start of an encoded block. The number before [ (the repeat count) is read character by character. Since k can have several digits, we accumulate count in a loop, adding each new digit while taking its position into account (multiplying by 10).
  3. After reading count and finding the opening bracket [, the algorithm looks for the matching closing bracket ]. This is done with a counter bracket, which is incremented on [ and decremented on ], so nested brackets are handled correctly.
  4. Once the matching closing bracket is found, we cut out the substring between [ and ] and call decodeString on it recursively. The result of that call is repeated count times and appended to the overall result res.
  5. The index i is moved to the position of the closing bracket to continue traversing the string after the processed block.
typescript
export const decodeString = (s: string): string => {
  let res = '';
 
  for (let i = 0; i < s.length; i++) {
    if (s[i] >= 'a' && s[i] <= 'z') {
      res += s[i];
      continue;
    }
 
    let count = 0;
    while (s[i] != '[') {
      count = count * 10 + Number(s[i]);
      i++;
    }
 
    let bracket = 1;
    let j = i + 1;
    while (bracket > 0) {
      if (s[j] == '[') {
        bracket++;
      }
 
      if (s[j] == ']') {
        bracket--;
      }
 
      j++;
    }
 
    res += decodeString(s.substring(i + 1, j - 1)).repeat(count);
 
    i = j - 1;
  }
 
  return res;
};

Complexity Analysis

Time Complexity

The complexity is O(maxk * n), where maxk is the maximum value of k and n is the length of the string s.

Space Complexity

O(n): the space used by the call stack for the recursion. Since we decode each nested pattern recursively, the maximum depth of the recursion stack does not exceed n.