Skip to content

Commit 7736544

Browse files
authored
feat: java for $20
2 parents 7506bf7 + f679eba commit 7736544

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

problems/20.valid-parentheses.md

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ https://leetcode-cn.com/problems/valid-parentheses/description
8888

8989
### 代码
9090

91-
代码支持:JS,Python
91+
代码支持:JS,Python,Java,C++
9292

9393
Javascript Code:
9494

@@ -150,6 +150,66 @@ Python Code:
150150
return len(stack) == 0
151151
```
152152

153+
Java Code:
154+
155+
```java
156+
class Solution {
157+
public boolean isValid(String s) {
158+
//1.判断空字符串
159+
if(s.isEmpty()) return true;
160+
//2.创建辅助栈
161+
Stack<Character> stack = new Stack<>();
162+
//3.仅遍历一次
163+
for(char c : s.toCharArray()){
164+
if(c == '('){
165+
stack.push(')');
166+
}else if(c == '['){
167+
stack.push(']');
168+
}else if(c == '{'){
169+
stack.push('}');
170+
}else if(stack.isEmpty() || c != stack.pop()){
171+
return false;
172+
}
173+
}
174+
//4.返回
175+
return stack.isEmpty();
176+
}
177+
}
178+
```
179+
180+
C++ Code:
181+
182+
```cpp
183+
class Solution {
184+
public:
185+
bool isValid(string s) {
186+
int n = s.size();
187+
if (n % 2 == 1) {
188+
return false;
189+
}
190+
191+
unordered_map<char, char> pairs = {
192+
{')', '('},
193+
{']', '['},
194+
{'}', '{'}
195+
};
196+
stack<char> stk;
197+
for (char ch: s) {
198+
if (pairs.count(ch)) {
199+
if (stk.empty() || stk.top() != pairs[ch]) {
200+
return false;
201+
}
202+
stk.pop();
203+
}
204+
else {
205+
stk.push(ch);
206+
}
207+
}
208+
return stk.empty();
209+
}
210+
};
211+
```
212+
153213
**复杂度分析**
154214

155215
- 时间复杂度:$O(N)$

0 commit comments

Comments
 (0)