leetcode20.有效的括号
作者:互联网
https://leetcode-cn.com/problems/valid-parentheses/
class Solution {
public boolean isValid(String s) {
Deque<Character> l = new LinkedList<>();
char[] arr = s.toCharArray();
Set<Character> left = new HashSet<>();
Set<Character> right = new HashSet<>();
left.add('(');
left.add('[');
left.add('{');
right.add(']');
right.add(')');
right.add('}');
for(int i = 0;i < s.length();i++) {
if(right.contains(arr[i])) {
//考虑左括号为空,出现了右括号,则直接返回false
if(l.size() == 0) return false;
if(arr[i] == ')' && l.pollLast() == '(') continue;
if(arr[i] == ']' && l.pollLast() == '[') continue;
if(arr[i] == '}' && l.pollLast() == '{') continue;
//如果左右括号不符合,也返回false
return false;
} else l.addLast(arr[i]);
}
//这里有左右括号都消除了,但是左括号有多余的
return l.size() == 0 ? true : false;
}
}
标签:arr,right,false,有效,括号,add,leetcode20,left 来源: https://blog.csdn.net/qq_37931960/article/details/119083531