-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.java
40 lines (36 loc) · 1.08 KB
/
Solution.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
37
38
39
40
package leetcode.algo.stack.leet_en_20;
import java.util.Stack;
public class Solution {
/*
* 20. Valid Parentheses(合法/有效的括号)
* 执行用时 : 13 ms
* 内存消耗 : 35.4 MB
* */
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == ']') {
if (stack.isEmpty() || '[' != stack.pop()) {
return false;
}
} else if (c == '}') {
if (stack.isEmpty() || '{' != stack.pop()) {
return false;
}
} else if (c == ')') {
if (stack.isEmpty() || '(' != stack.pop()) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
Solution ss = new Solution();
String str = "([)]";
System.out.println(ss.isValid(str));
}
}