-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
56 lines (52 loc) · 1.61 KB
/
ValidParentheses.java
File metadata and controls
56 lines (52 loc) · 1.61 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
package easy;
import java.util.LinkedList;
import java.util.List;
/**
*
* ClassName: ValidParentheses
* @author chenyiAlone
* Create Time: 2018/11/30 13:10:57
* Description: No.20 使用了LinkedList栈操作完成了匹配
*/
public class ValidParentheses {
public boolean isValid(String s) {
LinkedList stack = new LinkedList();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '(':
case '{':
case '[':
stack.push(c);
break;
case ')':
case '}':
case ']':
// System.out.println("c = " + c + " match(c) = " + match(c) + " peek() = " + stack.peek());
if (stack.peek() == null || !stack.pop().equals(match(c)))
return false;
// System.out.println("执行这一句!!");
break;
}
}
if (stack.size() == 0) return true;
else return false;
}
public static char match(char c) {
switch (c) {
case ')':
return '(';
case '}':
return '{';
case ']':
return '[';
default:
return ' ';
}
}
public static void main(String[] args) {
String s = "()";
System.out.println(new ValidParentheses().isValid(s));
// System.out.println(new Character('c').equals('c'));
}
}