valid parentheses

Hana Sato 9 months ago
parent 059b3d34c2 commit 653cc03324b289f80bef2349f785eb346d16fa38
1 changed files with 9 additions and 0 deletions
+9-0valid_parentheses.py ADDED
View File
@@ -0,0 +1,9 @@
1+def is_valid(s):
2+ pairs = {")": "(", "]": "[", "}": "{"}
3+ stack = []
4+ for ch in s:
5+ if ch in pairs.values():
6+ stack.append(ch)
7+ elif not stack or stack.pop() != pairs[ch]:
8+ return False
9+ return not stack