-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValid_Parenthesis_Day21.py
More file actions
53 lines (44 loc) · 1.26 KB
/
Copy pathValid_Parenthesis_Day21.py
File metadata and controls
53 lines (44 loc) · 1.26 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
#Brute Force code
from socketserver import TCPServer
class Solution:
def isValid(self, s: str) -> bool:
prev_length = -1
while prev_length != len(s):
prev_length = len(s)
s = s.replace("()", "").replace("{}", "").replace("[]", "")
return s == ""
# TC - O(n²)
# SC - O(1)
#Better Approach
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for ch in s:
if ch in "({[":
stack.append(ch)
else:
if not stack:
return False
top = stack.pop()
if (ch == ')' and top != '(') or \
(ch == '}' and top != '{') or \
(ch == ']' and top != '['):
return False
return not stack
# TC - O(n)
# SC - O(n)
#Optimal Approach
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping:
top_element = stack.pop() if stack else '#'
if mapping[char] != top_element:
return False
else:
stack.append(char)
return not stack
# TC - O(n)
# SC - O(n)