Skip to content

✨ (solution): Problem 20. Valid Parentheses #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions solutions/20. Valid Parentheses/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
---
comments: true
difficulty: easy
# Follow `Topics` tags
tags:
- String
- Stack
---

# [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)

## Description

You are given a string s that consists only of the characters `(`, `)`, `{`, `}`, `[`, and `]`. Your task is to determine whether the string is valid.

A string is considered valid if it meets the following conditions:

1. Every opening bracket has a matching closing bracket of the same type.
2. Brackets must close in the correct order (i.e., the most recently opened bracket must be the first one to close).
3. There should not be any unmatched brackets.


**Example 1:**
```
Input: s = "{}"
Output: true
```

**Example 2:**
```
Input: s = "{]"
Output: false
```


**Constraints:**
`1 <= s.length <= 104`
`s` consists of parentheses only `'()[]{}'`.

## Solution

As known valid combination:
```
mapping = { ')': '(', '}': '{', ']': '[' }
```

Let stack has only open parentheses. When a close parenthesis comes, use it as a key to get valid open parenthesis in the mapping. If mapped parentheses and stack top parenthese sare not valid combination, we should return False.

At last, if stack is empty, we should return True.

```java
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
}
```

```python
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping.values():
stack.append(char)
elif char in mapping:
if stack == [] or mapping[char] != stack.pop():
return False
return not stack
```

## Complexity

- Time complexity: $$O(n)$$
<!-- Add time complexity here, e.g. $$O(n)$$ -->

- Space complexity: $$O(n)$$
<!-- Add space complexity here, e.g. $$O(n)$$ -->
21 changes: 21 additions & 0 deletions solutions/20. Valid Parentheses/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import java.util.Stack;

class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
}
11 changes: 11 additions & 0 deletions solutions/20. Valid Parentheses/Solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping.values():
stack.append(char)
elif char in mapping:
if stack == [] or mapping[char] != stack.pop():
return False
return not stack
Loading