class Solution {
public boolean isValid(String s) {
Set<Character> left = new HashSet<>();
Set<Character> right = new HashSet<>();
left.add('(');
left.add('{');
left.add('[');
right.add('}');
right.add(']');
right.add(')');
Deque<Character> st = new LinkedList<>();
if(right.contains(s.charAt(0))) return false;
st.addLast(s.charAt(0));
for(int i = 1; i < s.length();i++){
if(right.contains(s.charAt(i))){
if(st.size() > 0){
char a = st.pollLast();
if(!judge(a,s.charAt(i))) return false;
} else return false;
}else{
st.addLast(s.charAt(i));
}
}
if(st.size() > 0) return false;
return true;
}
public boolean judge(char a,char b){
if(a == '(' && b == ')') return true;
if(a == '{' && b == '}') return true;
if(a == '[' && b == ']') return true;
return false;
}
}
20. 有效的括号
最新推荐文章于 2022-12-07 11:27:56 发布