-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path20.Valid-Parentheses.py
39 lines (34 loc) · 999 Bytes
/
20.Valid-Parentheses.py
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
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
#
# algorithms
# Easy (33.62%)
# Total Accepted: 437.1K
# Total Submissions: 1.3M
# beats 33.88% of python submissions
from collections import deque
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = deque()
for ch in s:
if ch == '(' or ch == '[' or ch == '{' or len(stack) == 0:
stack.append(ch)
elif ch == ')':
if stack[-1] == '(':
stack.pop()
else:
stack.append(ch)
elif ch == ']':
if stack[-1] == '[':
stack.pop()
else:
stack.append(ch)
elif ch == '}':
if stack[-1] == '{':
stack.pop()
else:
stack.append(ch)
return len(stack) == 0