Skip to content

Commit 67ac26b

Browse files
committed
feat: finish valid parentheses in python
1 parent 3417705 commit 67ac26b

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

alternative/easy/valid_parentheses.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
def is_valid(s):
2+
stack = []
3+
for c in s:
4+
if c in "([{":
5+
stack.append(c)
6+
elif c == ')' and (not stack or stack.pop() != '('):
7+
return False
8+
elif c == ']' and (not stack or stack.pop() != '['):
9+
return False
10+
elif c == '}' and (not stack or stack.pop() != '{'):
11+
return False
12+
return not stack
13+
14+
# Test cases
15+
assert is_valid("()") == True
16+
assert is_valid("()[]{}") == True
17+
assert is_valid("(]") == False
18+
assert is_valid("([)]") == False
19+
assert is_valid("{[]}") == True

0 commit comments

Comments
 (0)