-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDecodeStrings_Day37.py
More file actions
76 lines (65 loc) · 1.96 KB
/
Copy pathDecodeStrings_Day37.py
File metadata and controls
76 lines (65 loc) · 1.96 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#Brute Force Approach
class Solution:
def decodeString(self, s: str) -> str:
def decode(i):
res = ""
num = 0
while i < len(s):
if s[i].isdigit():
num = num * 10 + int(s[i])
elif s[i] == '[':
decoded_str, i = decode(i + 1)
res += num * decoded_str
num = 0
elif s[i] == ']':
return res, i
else:
res += s[i]
i += 1
return res, i
result, _ = decode(0)
return result
# Time Complexity: O(k * n)
# Space Complexity: O(n)
#Better Approach
class Solution:
def decodeString(self, s: str) -> str:
stack = []
curr_str = ""
curr_num = 0
for char in s:
if char.isdigit():
curr_num = curr_num * 10 + int(char)
elif char == '[':
stack.append((curr_str, curr_num))
curr_str = ""
curr_num = 0
elif char == ']':
last_str, num = stack.pop()
curr_str = last_str + num * curr_str
else:
curr_str += char
return curr_str
# Time Complexity: O(n)
# Space Complexity: O(n)
#Optimal Approach
class Solution:
def decodeString(self, s: str) -> str:
stack = []
curr_str = []
curr_num = 0
for char in s:
if char.isdigit():
curr_num = curr_num * 10 + int(char)
elif char == '[':
stack.append((''.join(curr_str), curr_num))
curr_str = []
curr_num = 0
elif char == ']':
last_str, num = stack.pop()
curr_str = list(last_str) + curr_str * num
else:
curr_str.append(char)
return ''.join(curr_str)
# Time Complexity: O(n)
# Space Complexity: O(n)