-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathID20ValidParentheses.java
40 lines (34 loc) · 1.18 KB
/
ID20ValidParentheses.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.editor.cn;
import java.util.Stack;
public class ID20ValidParentheses {
public static void main(String[] args) {
Solution solution = new ID20ValidParentheses().new Solution();
// 执行测试
solution.isValid("(])");
System.out.println("");
}
// leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean isValid(String s) {
boolean ans = true;
char[] chars = s.toCharArray();
Stack<Character> stack = new Stack<>();
for (char c : chars) {
if (stack.isEmpty())
stack.push(c);
else {
if (c == ')' && stack.peek() == '(')
stack.pop();
else if (c == '}' && stack.peek() == '{')
stack.pop();
else if ((c == ']' && stack.peek() == '['))
stack.pop();
else
stack.push(c);
}
}
return stack.isEmpty();
}
}
// leetcode submit region end(Prohibit modification and deletion)
}