Skip to content

Commit 3089acd

Browse files
committed
Add #0020 Valid Parentheses
1 parent 942e2f0 commit 3089acd

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

#0020 Valid Parentheses.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
"""
4+
Determine if the input string s has valid parentheses.
5+
6+
Args:
7+
s (str): Input string consisting of parentheses '(', ')', '[', ']', '{', '}'
8+
9+
Returns:
10+
bool: True if the parentheses are valid, False otherwise.
11+
"""
12+
# Mapping of opening to closing parentheses
13+
entries = {
14+
"(": ")",
15+
"[": "]",
16+
"{": "}"
17+
}
18+
19+
stack = []
20+
21+
for c in s:
22+
if c in entries:
23+
# Push corresponding closing bracket onto the stack
24+
stack.append(entries[c])
25+
else:
26+
# If stack is empty or the top of stack doesn't match current character
27+
if not stack or stack.pop() != c:
28+
return False
29+
30+
# Stack should be empty if all opening brackets had matching closing brackets
31+
return not stack
32+

0 commit comments

Comments
 (0)