forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsValid.java
More file actions
48 lines (43 loc) · 1.01 KB
/
IsValid.java
File metadata and controls
48 lines (43 loc) · 1.01 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
package normal;
import java.util.Stack;
/**
* @program JavaBooks
* @description: 20.有效的括号
* @author: mf
* @create: 2019/11/07 10:20
*/
/*
题目:https://leetcode-cn.com/problems/valid-parentheses/
类型:栈
难度:easy
*/
/*
输入: "()"
输出: true
输入: "()[]{}"
输出: true
输入: "(]"
输出: false
*/
public class IsValid {
public static void main(String[] args) {
String s = "()";
System.out.println(isValid(s));
}
private static boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (stack.size() == 0) {
stack.push(c);
} else if (isSym(stack.peek(), c)) {
stack.pop();
} else {
stack.push(c);
}
}
return stack.size() == 0;
}
private static boolean isSym(char c1, char c2) {
return (c1 == '(' && c2 == ')') || (c1 == '[' && c2 == ']') || (c1 == '{' && c2 == '}');
}
}