-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses_20.java
More file actions
41 lines (38 loc) · 1.2 KB
/
Copy pathValidParentheses_20.java
File metadata and controls
41 lines (38 loc) · 1.2 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
package Stack_Queue;
import java.util.Deque;
import java.util.LinkedList;
/**
* 有效的括号,左括号必须用相同类型的右括号闭合。左括号必须以正确的顺序闭合。
*/
public class ValidParentheses_20 {
public boolean isValid(String s) {
char[] str=s.toCharArray();
Deque<Character> queue=new LinkedList<>();
for(char c:str){
if('('==c||'['==c||'{'==c){
queue.push(c);
}else{
if(!queue.isEmpty()){
char cur=queue.peek();
if(c==')'&&cur!='('){
return false;
}else if(c==']'&&cur!='['){
return false;
}else if(c=='}'&&cur!='{'){
return false;
}else{
queue.pop();
}
}else{
return false;
}
}
}
return queue.isEmpty();
}
public static void main(String[] args) {
ValidParentheses_20 test = new ValidParentheses_20();
boolean valid = test.isValid("([)]");
System.out.println(valid);
}
}