20. Valid Parentheses
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.
判断字符括号是否匹配正确。
java代码:
public class Solution { public boolean isValid(String s) { Stack a=new Stack(); int i=0; while(i!=s.length()){ switch(s.charAt(i)){ case '[': a.push('['); break; case '(': a.push('('); break; case '{': a.push('{'); break; case ')': if(a.empty()||(char)a.pop()!='(') return false; break; case '}': if(a.empty()||(char)a.pop()!='{') return false; break; case ']': if(a.empty()||(char)a.pop()!='[') return false; break; } i++; } if(!a.empty()){ return false; } return true; } }