forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidParentheses.java
36 lines (35 loc) · 1 KB
/
ValidParentheses.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
/**
* 要注意栈判空
*/
public class ValidParentheses {
// 耗时4ms
public boolean isValid(String s) {
int[] stack = new int[s.length()];
int index = 0;
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '(':
case '[':
case '{':
stack[index++] = i;
break;
case ')':
if (index == 0 || s.charAt(stack[--index]) != '(') {
return false;
}
break;
case ']':
if (index == 0 || s.charAt(stack[--index]) != '[') {
return false;
}
break;
case '}':
if (index == 0 || s.charAt(stack[--index]) != '{') {
return false;
}
break;
}
}
return index == 0;
}
}