-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20.java
77 lines (71 loc) · 2.21 KB
/
20.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{')
stack.push(s.charAt(i));
else {
if (stack.size() != 0) {
if (stack.peek() - s.charAt(i) == '(' - ')' || stack.peek() - s.charAt(i) == '[' - ']'
|| stack.peek() - s.charAt(i) == '{' - '}') {
stack.pop();
}
else
return false;
}
else
return false;
}
}
if (stack.size() != 0)
return false;
else
return true;
}
}
// 第二次做法
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i = 0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='[')
stack.push(s.charAt(i));
else{
if(stack.isEmpty())
return false;
Character ch = stack.peek();
if(s.charAt(i)-ch==1||s.charAt(i)-ch==2){
stack.pop();
}
else{
return false;
}
}
}
if(!stack.isEmpty())
return false;
return true;
}
}
// 第三次做法
class Solution {
public boolean isValid(String s) {
if(s.length()%2!=0){
return false;
}
Map<Character,Character> map = new HashMap<>();
map.put(')','(');
map.put(']','[');
map.put('}','{');
Deque<Character> stack = new ArrayDeque<>();
for(char c : s.toCharArray()){
if(!map.containsKey(c)){ // 是左括号
stack.push(c);
}
else if(stack.isEmpty()||stack.pop()!=map.get(c)){ // 如果是右括号则自动弹出并跳过循环,不是右括号就返回false
return false;
}
}
return stack.isEmpty();
}
}