valid parentheses
1 changed files with 9 additions and 0 deletions
valid_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 | |