-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecode_string.py
More file actions
39 lines (37 loc) · 1.05 KB
/
decode_string.py
File metadata and controls
39 lines (37 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Problem: Decode String
# (https://leetcode.com/problems/decode-string/description/)
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
i = 0
while 1:
if i >= len(s):
return "".join(stack)
if s[i].isdigit():
start = i
while s[i].isdigit():
i += 1
num = s[start:i]
stack.append(num)
continue
if s[i] == ']':
word = []
while stack[-1].isalpha():
word.append(stack[-1])
stack.pop()
word.reverse()
numTimes = int(stack[-1])
stack.pop()
word = word * numTimes
stack.append("".join(word))
i += 1
continue
if s[i] == '[':
i += 1
continue
stack.append(s[i])
i += 1