-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathvalid_parentheses.py
More file actions
80 lines (64 loc) · 1.86 KB
/
valid_parentheses.py
File metadata and controls
80 lines (64 loc) · 1.86 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
77
78
79
80
"""
The challenge then is to write an algorithm that will read a string of parentheses from left to right and decide whether the symbols are balanced
"""
# Leetcode: https://leetcode.com/problems/valid-parentheses/
from stack import Stack
#For different types of parentheses
# O(N) Solution
def checks(open, close):
opener = "({["
closer = ")}]"
return opener.index(open) == closer.index(close)
def validParentheses(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol in "({[":
s.push(symbol)
else:
if s.isEmpty():
return False
else:
top = s.pop()
if not checks(top, symbol):
balanced = False
index += 1
if balanced and s.isEmpty():
return True
else:
return False
def isValid(s):
stack = []
mapping = {")": "(", "}": "{", "]": "["}
for char in s:
if char in mapping:
top = stack.pop() if stack else "*"
if mapping[char] != top:
return False
else:
stack.append(char)
return not stack
print(validParentheses('{({([][])}())}'))
print(isValid('[{()]'))
#For same type of braces
def valid_parenthesis(symbolString):
s = Stack()
balanced = True
index = 0
while index < len(symbolString) and balanced:
symbol = symbolString[index]
if symbol == "(":
s.push(symbol)
else:
if s.isEmpty():
balanced = False
else:
s.pop()
index += 1
if balanced and s.isEmpty():
return True
else:
return False
print(valid_parenthesis('((()))'))