Decode String

394. Decode String

Given an encoded string, return its decoded string.

Input: s = "3[a]2[bc]"
Output: "aaabcbc"
def decodeString(self, s: str) -> str:
    stack = []
    line = ''
    num = 0
    i = 0
    
    while i < len(s):
        c = s[i]
        if c.isdigit():
            num = int(c)
            while i+1 < len(s) and s[i+1].isdigit():
                num = 10*num + int(s[i+1])
                i += 1
        elif c == '[':
            stack.append(line)
            stack.append(num)
            line = ''
            num = 0
        elif c == ']':
            pre_num = stack.pop()
            pre_line = stack.pop()
            pre_line += line * pre_num
            line = pre_line
        else:
            line += c
        i += 1
    return line
  • Recursive: 放進recursion的string必須是完整[]的內容,並更新index

443. Decode Compression

Given an array of characters, compress it in-place.

Valid Express (Bloomberg)

Given a string of balanced expression, find if it contains a redundant parenthesis or not. A set of parenthesis are redundant if same sub-expression is surrounded by unnecessary or multiple brackets.

Compress String (Quantcast)

Write a method that can take a "compressed" string and decompress it.

Example:

"abc3" => "abccc"

"abc3def" => "abcccdef"

"abc[def]2abc" => "abcdefdefabc"

"abc[de2f]2abc" => "abcdeefdeefabc"

"abc[def[ghi]2def]2abc" => "abcdefghighidefdefghighidefabc"

  • Assumptions:

    • Every closing bracket is followed by a number

    • Each non numeric character is either a-z, [, or ]

  • mark有無需要concate的string

  • 碰到'['要找到對應']'的index

  • 碰到num兩種判斷: concate string or Char

    Recursive

Iterative(較難)

  • char & [string] 都視為一個element

  • 碰到char 放進stack

  • 碰到'[', poll stack until '[', 組成string再放進stack, push '['

  • 碰到']', poll stack until '[', 組成string再放進stack, poll '['

  • 數字就重複 poll的 string

  • 最後reverse string

Last updated

Was this helpful?