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.
思路:本题是栈的一个典型应用,括号匹配问题。思路太简单就不赘述了。
代码如下(已通过leetcode)
public class Solution {
public boolean isValid(String s) {
Stack stack= new Stack();
for(int i=0;i<s.length();i++) {
switch(s.charAt(i)){
case '(':
stack.push('(');
break;
case '{':
stack.push('{');
break;
case '[':
stack.push('[');
break;
case ')':
if(!stack.isEmpty()) {
char temp=(char) stack.pop();
if(temp!='(') return false;
else break;
} else return false;
case '}':
if(!stack.isEmpty()) {
char temp=(char) stack.pop();
if(temp!='{') return false;
else break;
} else return false;
case ']':
if(!stack.isEmpty()) {
char temp=(char) stack.pop();
if(temp!='[') return false;
else break;
} else return false;
}
}
if(stack.isEmpty()) return true;
else return false;
}
}