Leetcode 394 Solution

This article provides solution to leetcode question 394 (decode-string)

https://leetcode.com/problems/decode-string

Solution

class Solution: def decodeString(self, s: str) -> str: i = 0
def decode(): nonlocal s nonlocal i
if i == len(s): return ""
ans = ""
while i < len(s): if 'a' <= s[i] <= 'z': ans += s[i] i += 1 elif '0' <= s[i] <= '9': val = 0
while s[i] != '[': val = val * 10 + int(s[i]) i += 1
i += 1
substr = decode() ans += substr * val elif s[i] == ']': i += 1 break else: raise Exception("Unexpected char '{}'!".format(s[i]))
return ans
return decode()