forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid-parentheses.py
More file actions
25 lines (23 loc) · 777 Bytes
/
Copy pathvalid-parentheses.py
File metadata and controls
25 lines (23 loc) · 777 Bytes
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
from __future__ import print_function
# Time: O(n)
# Space: O(n)
#
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
# determine if the input string is valid.
#
# The brackets must close in the correct order, "()" and "()[]{}"
# are all valid but "(]" and "([)]" are not.
#
class Solution:
# @return a boolean
def isValid(self, s):
stack, lookup = [], {"(": ")", "{": "}", "[": "]"}
for parenthese in s:
if parenthese in lookup:
stack.append(parenthese)
elif len(stack) == 0 or lookup[stack.pop()] != parenthese:
return False
return len(stack) == 0
if __name__ == "__main__":
print(Solution().isValid("()[]{}"))
print(Solution().isValid("()[{]}"))