-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution20.java
More file actions
45 lines (44 loc) · 1.34 KB
/
Solution20.java
File metadata and controls
45 lines (44 loc) · 1.34 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
import java.util.Stack;
/**
* Created by alex on 16-2-22.
*/
public class Solution20 {
public boolean isValid(String s) {
Stack<String> stack = new Stack<>();
for(int i = 0; i < s.length(); i++){
String character = s.substring(i, i+1);
switch (character){
case ")":
if(stack.isEmpty())
return false;
if(stack.peek().equals("(")){
stack.pop();
}else{
stack.push(character);
}
break;
case "}":
if(stack.isEmpty())
return false;
if(stack.peek().equals("{")){
stack.pop();
}else{
stack.push(character);
}
break;
case "]":
if(stack.isEmpty())
return false;
if(stack.peek().equals("[")){
stack.pop();
}else{
stack.push(character);
}
break;
default:
stack.push(character);
}
}
return stack.isEmpty();
}
}