20. Valid Parentheses
1 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 2 3 The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
给一串只包含有'('
, ')'
, '{'
, '}'
, '['
和']'
,的字符串,要求判定是否是合法的。
1 public boolean isValid(String s) { 2 Stack<Character> seq = new Stack<>(); 3 for (Character c:s.toCharArray()) 4 { 5 if (c=='(') seq.push(')'); 6 else if (c=='[') seq.push(']'); 7 else if (c=='{') seq.push('}'); 8 else if (seq.isEmpty() || seq.pop()!= c) return false; 9 } 10 return seq.isEmpty(); 11 }