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.
题意:括号匹配,要求同种括号一一对应,不能嵌套
思路:用栈存放左括号,若是遇到右括号则pop出比较,若是对不上则表示匹配失败。最终所有比较完后若是栈中不为空,则匹配失败,不然表示匹配成功
实现:
public class Solution {
public boolean isValid(String s ) {
List< Character> left=new LinkedList<Character>();
char[]arr =s .toCharArray();
for(int i =0;i <s .length();i++){
if(arr [i ]=='(' ||arr [i ]=='[' ||arr [i ]=='{' )//若是是左括号,则入栈
left.add( arr[ i]);
else{
if(left .size()==0)//若是栈为空,则匹配不成功
return false ;
char t =left .get(left .size()-1);//取出栈顶元素
left.remove( left.size()-1);
switch(arr [i ]){
case ')' :
if(t !='(' )
return false ;
break;
case ']' :
if(t !='[' )
return false ;
break;
case '}' :
if(t !='{' )
return false ;
break;
}
}
}
if(left .size()!=0)//若是栈不为空,表示左括号多了,匹配不成功
return false ;
return true ;
}
}