-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVp.java
More file actions
61 lines (56 loc) · 1.67 KB
/
Vp.java
File metadata and controls
61 lines (56 loc) · 1.67 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
package ValidParentheses020;
import java.util.Stack;
/**
* Created by Administrator on 2017/8/30.
*/
public class Vp {
//方法1。把括号左边({[压入堆栈,与下一个对比,相同则出栈
/*public boolean isValidParentheses(String s){
Stack<Character> stack=new Stack<Character>();
for(Character c:s.toCharArray()){
if("({[".contains(String.valueOf(c))){
stack.push(c);
}else{
if(!stack.isEmpty()&&is_valid(stack.peek(),c)){
stack.pop();
}else{
return false;
}
}
}
return stack.isEmpty();
}
private boolean is_valid(char c1,char c2){
return (c1=='('&&c2==')')||(c1=='{'&&c2=='}')||(c1=='['&&c2==']');
}*/
//方法2
public boolean isValidParentheses(String s){
Stack<Character> stack=new Stack<Character>();
for(char c:s.toCharArray()){
if(c=='('||c=='{'||c=='['){
stack.push(c);
}
if(c==')'){
if(stack.isEmpty()||stack.pop()!='('){
return false;
}
}
if(c==']'){
if(stack.isEmpty()||stack.pop()!='['){
return false;
}
}
if(c=='}'){
if(stack.isEmpty()||stack.pop()!='{'){
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args){
String s="([)]";
boolean res=new Vp().isValidParentheses(s);
System.out.print(res);
}
}