Skip to content

Commit b54ef8a

Browse files
committed
✨ (solution): Problem 20. Valid Parentheses
Add Solution of 20. Valid Parentheses
1 parent 321cacd commit b54ef8a

File tree

3 files changed

+125
-0
lines changed

3 files changed

+125
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
---
2+
comments: true
3+
difficulty: easy
4+
# Follow `Topics` tags
5+
tags:
6+
- String
7+
- Stack
8+
---
9+
10+
# [20. Valid Parentheses](https://leetcode.com/problems/valid-parentheses/description/)
11+
12+
## Description
13+
14+
You are given a string s that consists only of the characters `(`, `)`, `{`, `}`, `[`, and `]`. Your task is to determine whether the string is valid.
15+
16+
A string is considered valid if it meets the following conditions:
17+
18+
1. Every opening bracket has a matching closing bracket of the same type.
19+
2. Brackets must close in the correct order (i.e., the most recently opened bracket must be the first one to close).
20+
3. There should not be any unmatched brackets.
21+
22+
23+
**Example 1:**
24+
```
25+
Input: s = "{}"
26+
Output: true
27+
```
28+
29+
**Example 2:**
30+
```
31+
Input: s = "{]"
32+
Output: false
33+
```
34+
35+
36+
**Constraints:**
37+
`1 <= s.length <= 104`
38+
`s` consists of parentheses only `'()[]{}'`.
39+
40+
## Solution
41+
42+
As known valid combination:
43+
```
44+
mapping = { ')': '(', '}': '{', ']': '[' }
45+
```
46+
47+
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.
48+
49+
At last, if stack is empty, we should return True.
50+
51+
```java
52+
class Solution {
53+
public boolean isValid(String s) {
54+
Stack<Character> stack = new Stack<>();
55+
for (char c : s.toCharArray()) {
56+
if (c == '(' || c == '{' || c == '[') {
57+
stack.push(c);
58+
} else {
59+
if (stack.isEmpty()) {
60+
return false;
61+
}
62+
char top = stack.pop();
63+
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
64+
return false;
65+
}
66+
}
67+
}
68+
return stack.isEmpty();
69+
}
70+
}
71+
```
72+
73+
```python
74+
class Solution:
75+
def isValid(self, s: str) -> bool:
76+
stack = []
77+
mapping = {')': '(', '}': '{', ']': '['}
78+
for char in s:
79+
if char in mapping.values():
80+
stack.append(char)
81+
elif char in mapping:
82+
if stack == [] or mapping[char] != stack.pop():
83+
return False
84+
return not stack
85+
```
86+
87+
## Complexity
88+
89+
- Time complexity: $$O(n)$$
90+
<!-- Add time complexity here, e.g. $$O(n)$$ -->
91+
92+
- Space complexity: $$O(n)$$
93+
<!-- Add space complexity here, e.g. $$O(n)$$ -->
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import java.util.Stack;
2+
3+
class Solution {
4+
public boolean isValid(String s) {
5+
Stack<Character> stack = new Stack<>();
6+
for (char c : s.toCharArray()) {
7+
if (c == '(' || c == '{' || c == '[') {
8+
stack.push(c);
9+
} else {
10+
if (stack.isEmpty()) {
11+
return false;
12+
}
13+
char top = stack.pop();
14+
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
15+
return false;
16+
}
17+
}
18+
}
19+
return stack.isEmpty();
20+
}
21+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
class Solution:
2+
def isValid(self, s: str) -> bool:
3+
stack = []
4+
mapping = {')': '(', '}': '{', ']': '['}
5+
for char in s:
6+
if char in mapping.values():
7+
stack.append(char)
8+
elif char in mapping:
9+
if stack == [] or mapping[char] != stack.pop():
10+
return False
11+
return not stack

0 commit comments

Comments
 (0)