-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
56 lines (53 loc) · 1.54 KB
/
ValidParentheses.java
File metadata and controls
56 lines (53 loc) · 1.54 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/*
* https://leetcode.com/problems/valid-parentheses/
*/
public class ValidParentheses {
public boolean isValid(String s) {
Map<Character, Integer> parentheses = new HashMap<>();
parentheses.put('(', 1);
parentheses.put(')', 1);
parentheses.put('{', 2);
parentheses.put('}', 2);
parentheses.put('[', 3);
parentheses.put(']', 3);
if (s.isEmpty()) {
return true;
}
if ((s.length() & 1) != 0) {
return false;
}
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '(':
case '{':
case '[':
stack.push(parentheses.get(c));
break;
case ')':
case '}':
case ']':
if (!checkAndPopStack(stack, parentheses.get(c))) {
return false;
}
break;
default:
return false;
}
}
return stack.size() == 0;
}
private boolean checkAndPopStack(Stack<Integer> stack, int i) {
if (stack.isEmpty()) {
return false;
}
return stack.pop() == i;
}
public static void main(String[] args) {
System.out.println(new ValidParentheses().isValid("{[]}()")); // true
}
}