一、Description:
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.
二、Ideas:
该问题的目的是实现给定括号的配对。很容易想到,可以使用入栈出栈的方法(类似于自动机),可以想象,自动机的初始监测点从字符串的头开始检测,如果第一个检测到的字符为向左开口的形式,那么就一定没有与其配对的,直接退出检测;如果不然,则将检测到的字符入栈,并继续向右移动监测点。这时,若检测到开口向左的,则与栈顶字符进行配对,若配对成功则继续向后检测,若配对失败则直接退出。此后,重复上一过程,直到检测完所有的字符。另外,由于括号可以配对的必要条件之一是字符个数必须为偶数,所以可以在最开始检查字符串个数,这样可以避免不必要的操作。
三、Code:
class Solution {
public boolean isValid(String s) {
if(s.length()%2==1) return false;
Stack<Character> st=new Stack<Character>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{'){
st.push(s.charAt(i));
}
else if(i==0){
return false;
}
else{
if(s.charAt(i)==')'&&st.peek()=='('){
st.pop();
}
else if(s.charAt(i)==']'&&st.peek()=='[') {
st.pop();
}
else if(s.charAt(i)=='}'&&st.peek()=='{') {
st.pop();
}
else break;
}
}
return st.isEmpty();
}
}