forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid-parentheses.py
More file actions
38 lines (35 loc) · 1.08 KB
/
valid-parentheses.py
File metadata and controls
38 lines (35 loc) · 1.08 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
#https://leetcode.com/problems/valid-parentheses/
class Solution(object):
def isValid(self, s):
if (s==''):
return True
elif ('()' in s):
return self.isValid(s.replace('()', ''))
elif ('[]' in s):
return self.isValid(s.replace('[]', ''))
elif ('{}' in s):
return self.isValid(s.replace('{}', ''))
else:
return False
class Solution(object):
def isValid(self, s):
stack = []
for c in s:
if c=='(' or c=='[' or c=='{':
stack.append(c)
elif c==')':
if stack and stack[-1]=='(':
stack.pop()
else:
stack.append(c)
elif c==']':
if stack and stack[-1]=='[':
stack.pop()
else:
stack.append(c)
elif c=='}':
if stack and stack[-1]=='{':
stack.pop()
else:
stack.append(c)
return len(stack)==0