mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 21:22:43 +00:00
77 lines
1.7 KiB
Plaintext
77 lines
1.7 KiB
Plaintext
---
|
|
title: '20. Valid Parentheses'
|
|
description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid
|
|
icon: dot
|
|
topics:
|
|
- { name: "String", slug: "string" }
|
|
- { name: "Stack", slug: "stack" }
|
|
- { name: "Bracket Sequences", slug: "bracket-sequences" }
|
|
video: "WTzjTskDFMg"
|
|
sidebar:
|
|
label: 'Valid Parentheses'
|
|
badge: 'Easy'
|
|
---
|
|
|
|
### 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
|
|
```
|