Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
Subscribe to see which companies asked this question
这个就是括号匹配,用数据结构中的栈就可以解决
public class Solution {
public boolean isValid(String s) {
LinkedList<Character> linkedList=new LinkedList<>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)!='('&&s.charAt(i)!='['&&s.charAt(i)!='{'){
if(linkedList.isEmpty()){
return false;
}else{
switch(linkedList.pop()){
case '(':
if(s.charAt(i)!=')')return false;break;
case '[':
if(s.charAt(i)!=']')return false;break;
case '{':
if(s.charAt(i)!='}')return false;break;
}
}
}else{
linkedList.push(s.charAt(i));
}
}
if(linkedList.isEmpty())return true;
else return false;
}
}