-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQ20.java
36 lines (28 loc) · 879 Bytes
/
Q20.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
package algorithms;
import java.util.*;
public class Q20 {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<Character, Character>();
// map.put('(', ')');
map.put(')', '(');
// map.put('[', ']');
map.put(']', '[');
// map.put('{', '}');
map.put('}', '{');
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (!stack.isEmpty() && stack.peek() == map.get(c)) { // 栈顶元素
stack.pop();
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String s = "(){}}{";
Q20 q = new Q20();
boolean ans = q.isValid(s);
System.out.println(ans);
}
}