Files
leetcode/apps/docs/content/stack/20-valid-parentheses.mdx
T

77 lines
1.6 KiB
Plaintext

---
title: '20. Valid Parentheses'
description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid
sidebar:
label: 'Valid Parentheses'
badge: 'Easy'
---
<Badge variant="accent">String</Badge>
### Example 1:
- Input: `s = "()"`
- Output: `true`
### Example 2:
- Input: `s = "()[]{}"`
- Output: `true`
### Example 3:
- Input: `s = "(]"`
- Output: `false`
### Example 4:
- Input: `s = "([])"`
- Output: `true`
### Example 5:
- Input: `s = "([)]"`
- Output: `false`
### Constraints:
- `1 <= s.length <= 10^4`
- `s` consists of parentheses only '()[]{}'.
## Approach
```mermaid
flowchart TD
S(["isValid(s)"]) --> I["stack = [], pairs = closer to opener"]
I --> L{"more char c?"}
L -- no --> Z{"stack empty?"}
Z -- yes --> T(["return True"])
Z -- no --> U(["return False — unclosed openers left"])
L -- yes --> Q{"c is a closer?"}
Q -- no --> A["stack.append(c) — it is an opener"]
A --> L
Q -- yes --> M{"stack non-empty and pairs[c] == stack[-1]?"}
M -- yes --> P["stack.pop() — matched"]
P --> L
M -- no --> F(["return False — mismatch"])
```
## Solution
```py
class Solution:
def isValid(self, s: str) -> bool:
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for c in s:
if c in pairs:
if stack and pairs[c] == stack[-1]:
stack.pop()
else:
return False
else:
stack.append(c)
return True if not stack else False
```
## Explanation
<YouTube id="WTzjTskDFMg" title="Valid Parentheses - Stack - Leetcode 20 - Python" />