-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0020.java
More file actions
37 lines (33 loc) · 1 KB
/
Copy pathLeetCode0020.java
File metadata and controls
37 lines (33 loc) · 1 KB
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
/* * Valid Parentheses
* Example:
* Input: s = "{[]}"
* Output: true
* */
import java.util.HashMap;
import java.util.Stack;
public class LeetCode0020 {
public static void main(String args[]) {
String s = "]";
System.out.println(isValid(s));
}
public static boolean isValid(String s) {
//根据括号构建哈希表
HashMap<Character, Character> hMap = new HashMap<Character, Character>();
hMap.put(')', '(');
hMap.put(']', '[');
hMap.put('}', '{');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (hMap.containsKey(c)) {
char top = stack.empty() ? '#' : stack.peek();
if (top == hMap.get(c))
stack.pop();
else
return false;
} else
stack.push(c);
}
return stack.empty();
}
}