Leetcode # 20. Valid Parentheses
- 2022.12.08
- LeetCode Parentheses Parsing Stack
https://leetcode.com/problems/valid-parentheses/
Solution
Time Complexity: O(len(s))
Space Complexity: O(len(s))
(The input and output generally do not count towards the space complexity.)
class Solution: def isValid(self, s: str) -> bool: stack = [] left_brackets = {"(", "[", "{"} right_brackets = {")": "(", "]": "[", "}": "{"} for c in s: if c in left_brackets: stack.append(c) elif not stack or stack.pop() != right_brackets[c]: return False return len(stack) == 0
Last Updated on 2023/08/16 by A1go