-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20.valid-parentheses.py
More file actions
50 lines (38 loc) · 1.1 KB
/
20.valid-parentheses.py
File metadata and controls
50 lines (38 loc) · 1.1 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
39
40
41
42
43
44
45
46
47
48
49
50
from typing import List
class Solution_one:
def isValid(self, s: str) -> bool:
stack: List[str] = []
for i in s:
if i in ("(", "[", "{"):
stack.append(i)
elif not stack:
return False
else:
if stack[-1] == "(" and i == ")":
stack.pop()
elif stack[-1] == "[" and i == "]":
stack.pop()
elif stack[-1] == "{" and i == "}":
stack.pop()
else:
return False
return not stack
# @leet start
class Solution:
def isValid(self, s: str) -> bool:
if len(s) < 2:
return False
mapping: dict[str, str] = {
")": "(",
"]": "[",
"}": "{",
}
stack: List[str] = []
for i in s:
if i in (")", "]", "}"):
if len(stack) == 0 or mapping[i] != stack.pop():
return False
else:
stack.append(i)
return bool(not stack)
# @leet end