-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path394_decode_string.py
More file actions
44 lines (30 loc) · 1.01 KB
/
394_decode_string.py
File metadata and controls
44 lines (30 loc) · 1.01 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
40
41
42
43
44
# LeetCode 394 Decode String
# URL: https://leetcode.com/problems/decode-string/
# Difficulty: Medium
# Language: Python 3.10+
class Solution(object):
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
current_string = ""
current_num = 0
for char in s:
if char.isdigit():
current_num = current_num * 10 + int(char)
elif char == "[":
stack.append((current_string, current_num))
current_string = ""
current_num = 0
elif char == "]":
prev_string, num = stack.pop()
current_string = prev_string + num * current_string
else:
current_string += char
return current_string
if __name__ == "__main__":
print(Solution().decodeString("3[a]2[bc]"))
print(Solution().decodeString("3[a2[c]]"))
print(Solution().decodeString("2[abc]3[cd]ef"))