Valid Parentheses
Examples
Example 1:
Input: s = "[]"
Output: true
Example 2:
Input: s = "([{}])"
Output: true
Example 3:
Input: s = "[(])"
Output: false
Explanation:
Example 1:
Input: s = "[]"
Output: true
Example 2:
Input: s = "([{}])"
Output: true
Example 3:
Input: s = "[(])"
Output: false
Explanation:
You are given a string s consisting of the following characters: '(', ')', '{', '}', '[' and ']'.
The input string s is valid if and only if:
Return true if s is a valid string, and false otherwise.
The brackets are not closed in the correct order.
1 <= s.length <= 10^4s consists only of parentheses characters ()[]{}Use a stack to track open brackets. When we see an opening bracket, push it. When we see a closing bracket, the top of the stack must be the matching opening bracket; otherwise the string is invalid. At the end, the stack must be empty. This correctly handles the empty string case.
The stack represents the order of unclosed opening brackets. A closing bracket must match the most recent opening bracket to preserve correct nesting. Any mismatch or leftover opening brackets means the string is invalid; if every close matches and the stack is empty, the string is valid.
O(n)O(n)class Solution:
def isValid(self, s: str) -> bool:
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return len(stack) == 0