Repository navigation
Expand file tree
/
Copy pathP20_Valid_Parentheses.java
More file actions
68 lines (63 loc) · 1.9 KB
/
Copy pathP20_Valid_Parentheses.java
File metadata and controls
68 lines (63 loc) · 1.9 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
57
58
59
60
61
62
63
64
65
66
67
68
package solution.easy;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* @author Yi-Lo
* 2020/10/23 15:53
* @version 1.0
* @topics Stack、String
* @urllink https://leetcode-cn.com/problems/valid-parentheses/
*/
public class P20_Valid_Parentheses {
public static boolean isValid_s1(String s) {
char[] arr = s.toCharArray();
Stack<Character> stack = new Stack();
for (int i = 0; i < arr.length; i++) {
char chr = arr[i];
if (chr == '(' || chr == '[' || chr == '{') {
stack.push(chr);
} else {
if (stack.size() > 0) {
int top = stack.peek();
if (top == (chr - 1) || top == (chr - 2)) {
stack.pop();
} else {
return false;
}
} else {
return false;
}
}
}
return stack.isEmpty();
}
public static boolean isValid_s2(String s) {
int len = s.length();
if (len % 2 == 1) {
return false;
}
Map<Character, Character> pair = new HashMap<>();
pair.put(')', '(');
pair.put(']', '[');
pair.put('}', '{');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (pair.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pair.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(isValid_s1("]"));
System.out.println(isValid_s1("(])"));
System.out.println(isValid_s1("()[]{}"));
}
}