题目:
给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
示例 1:
输入:s = "()" 输出:true
示例 2:
输入:s = "()[]{}" 输出:true
代码解析:
public boolean isValid(String s) {
//用于存放左括号
List<Character> left= new ArrayList<>();
for(int i=0;i<s.length();i++){
char ch = s.charAt(i);
//如果是左括号,就加入到列表
if(ch=='('||ch=='{'||ch=='['){
left.add(ch);
}else{
//如果是有括号,且长度为0,则是非法的
if(left.size()==0){
return false;
}
char lastChar = left.get(left.size()-1);
//如果左右括号匹配,则继续下一个字符
if((ch=='}'&&lastChar=='{')||(ch==')'&&lastChar=='(')||(ch==']'&&lastChar=='[')){
left.remove(left.size()-1);
continue;
}
return false;
}
}
//最后列表里的长度为0,则返回true
return left.size()==0;
}