-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode_0020.java
63 lines (53 loc) · 1.48 KB
/
LeetCode_0020.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.lijieyao.rabbitmq.hello;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* 力扣第20题
*/
public class LeetCode_0020 {
/**
* 给定一个只包括 '(',')','{','}','[',']'的字符串 s ,判断字符串是否有效。
*
* 有效字符串需满足:
*
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
*/
public static void main(String[] args) {
System.out.println(isValid("([)]"));
}
public static boolean isValid(String s) {
if (s.isEmpty()) {
return false;
}
Map<Character, Integer> map = new HashMap<>();
map.put('(', 1);
map.put('{', 2);
map.put('[', 3);
map.put(')', -1);
map.put('}', -2);
map.put(']', -3);
int sum = 0;
Stack<Integer> stack = new Stack<>();
for (char index : s.toCharArray()) {
if (!map.containsKey(index)) {
continue;
}
Integer tempInt = map.get(index);
if (stack.isEmpty() && tempInt <0){
return false;
}
sum += tempInt;
if (stack.isEmpty() || tempInt > 0) {
stack.push(tempInt);
continue;
}
if (stack.peek() != -tempInt){
return false;
}
stack.pop();
}
return sum == 0;
}
}