-
Notifications
You must be signed in to change notification settings - Fork 0
/
20. Valid Parentheses.java
37 lines (37 loc) · 1.09 KB
/
20. Valid Parentheses.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
class Solution {
public boolean isValid(String s) {
Stack<Character> st = new Stack<>();
st.push(s.charAt(0));
for (int i = 1; i < s.length(); i++){
char temp = s.charAt(i);
if(st.isEmpty() && (temp == ')' || temp == '}' || temp == ']')){
return false;
}
if(temp == '(' || temp == '{' || temp == '['){
st.push(temp);
} else if(temp == ')'){
char c = st.peek();
if(c == '('){
st.pop();
} else {
return false;
}
} else if(temp == '}'){
char c = st.peek();
if(c == '{'){
st.pop();
} else{
return false;
}
} else if(temp == ']'){
char c = st.peek();
if(c == '['){
st.pop();
} else {
return false;
}
}
}
return st.isEmpty();
}
}