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.
有效的括号。
此题可想到使用栈来作为辅助,遍历字符串,当字符与栈弹出字符匹配(组成括号),则遍历下一个,不匹配则将字符push到栈中。
至于为什么使用栈,自己举个例子,画图分析一下就行
class Solution { public boolean isValid(String s) {
//快速判断长度,长度不符合就直接返回false if(s==null||s.length()%2==1) return false; char[] c=s.toCharArray(); Stack<Character> stack=new Stack<>(); stack.push(c[0]); for(int i=1;i<c.length;i++){
//peek只是查看栈顶元素,不删除,pop要删除。
//这一串if,是查看是否匹配 if((c[i]=='}'&&stack.peek()=='{')|| (c[i]==']'&&stack.peek()=='[')|| (c[i]==')'&&stack.peek()=='(')){ stack.pop(); continue; } stack.push(c[i]); } return stack.isEmpty(); } }