-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCode_20.java
More file actions
34 lines (31 loc) · 1.09 KB
/
Copy pathleetCode_20.java
File metadata and controls
34 lines (31 loc) · 1.09 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
class Solution {
public boolean isValid(String s) {
Stack<String> stack = new Stack<>();
for(int i=0; i< s.length(); i++){
if(s.substring(i, i+1).equals("(") || s.substring(i, i+1).equals("[") || s.substring(i, i+1).equals("{")){
stack.push(s.substring(i, i+1));
}
else{
if(stack.isEmpty()){
return false;
}
if(s.substring(i, i+1).equals(")") ){
if(!stack.peek().equals("(")) return false;
stack.pop();
}
else if(s.substring(i, i+1).equals("}")){
if(!stack.peek().equals("{")) return false;
stack.pop();
}
else if(s.substring(i, i+1).equals("]")){
if(!stack.peek().equals("[")) return false;
stack.pop();
}
}
}
if(!stack.isEmpty()){
return false;
}
return true;
}
}