-
Notifications
You must be signed in to change notification settings - Fork 0
/
20.有效的括号.java
36 lines (34 loc) · 928 Bytes
/
20.有效的括号.java
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
import java.util.HashMap;
import java.util.Stack;
import java.util.Map;
/*
* @lc app=leetcode.cn id=20 lang=java
*
* [20] 有效的括号
*/
class Solution {
public boolean isValid(String s) {
Map<Character, Character> mapMap = new HashMap<>();
mapMap.put(']', '[');
mapMap.put('}', '{');
mapMap.put(')', '(');
boolean legal = false;
Stack<Character> stack = new Stack<Character>();
char[] a = s.toCharArray();
for(char item:a){
if(mapMap.values().contains(item)){
stack.push(item);
}else{
if(!stack.isEmpty()){
legal = stack.pop().equals(mapMap.get(item));
}else{
legal = false;
}
if(!legal){
return false;
}
}
}
return stack.isEmpty();
}
}