Skip to content

Commit cb688cb

Browse files
committed
use stack to solve parenthesis matching
1 parent 4701b64 commit cb688cb

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

python/020_Valid_Parentheses.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# class Solution(object):
22
# def isValid(self, s):
3-
3+
44
#
55
class Solution:
66
def isValid(self, s):
@@ -40,6 +40,23 @@ def isValid(self, s):
4040
else:
4141
return False
4242

43+
def isValid_stack(self, s):
44+
stack = []
45+
for i in s:
46+
if i in ['(', '{', '[']:
47+
stack.append(i)
48+
else:
49+
if len(stack) == 0:
50+
return False
51+
out_stack = stack.pop()
52+
if not ((out_stack == '(' and i == ')') or \
53+
(out_stack == '[' and i == ']') or \
54+
(out_stack == '{' and i == '}')):
55+
return False
56+
if len(stack) != 0: # make sure it is not single side column
57+
return False
58+
else:
59+
return True
4360

4461
# def isValid(self, s):
4562
# # python replace
@@ -57,3 +74,11 @@ def isValid(self, s):
5774
# return True
5875
# else:
5976
# return False
77+
78+
79+
if __name__ == '__main__':
80+
sinput = "()[]{}"
81+
gt = True
82+
s = Solution()
83+
out = s.isValid_stack(sinput)
84+
print(out)

0 commit comments

Comments
 (0)