-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy path20_ValidParentheses.py
More file actions
39 lines (29 loc) · 1007 Bytes
/
20_ValidParentheses.py
File metadata and controls
39 lines (29 loc) · 1007 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# coding: utf8
"""
题目链接: https://leetcode.com/problems/valid-parentheses/description.
题目描述:
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(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
if s[0] in [')', ']', '}']:
return False
stack = [s[0]]
for i in range(1, len(s)):
if s[i] == ')' and stack and stack[-1] == '(':
stack.pop()
elif s[i] == ']' and stack and stack[-1] == '[':
stack.pop()
elif s[i] == '}' and stack and stack[-1] == '{':
stack.pop()
else:
stack.append(s[i])
return True if not stack else False