-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathIsValid_20.java
More file actions
40 lines (35 loc) · 986 Bytes
/
IsValid_20.java
File metadata and controls
40 lines (35 loc) · 986 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.imood.msjava.leetcode;
import java.util.Stack;
/**
* @description: 用栈实现括号匹配
* @author: 微信公众号:码上Java
* @createDate: 2020/7/29/0029
*/
public class IsValid_20 {
/**
* 用栈实现括号匹配
*
* @param s
* @return
*/
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 cStack = stack.pop();
boolean b1 = c == ')' && cStack != '(';
boolean b2 = c == ']' && cStack != '[';
boolean b3 = c == '}' && cStack != '{';
if (b1 || b2 || b3) {
return false;
}
}
}
return stack.isEmpty();
}
}