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.
分析:
判断括号合法性的问题,涉及栈的使用。
栈保存左括号,遇见左括号压栈,遇见右括号检查栈顶,匹配则弹栈,不匹配则说明不合法。
public class Solution {
public boolean isValid(String s) {
if(s==null || s.length()==0 )
return false;
Stack<Character> st = new Stack<Character>();
for(int i=0; i<s.length(); i++){
char ch = s.charAt(i);
//左括号入栈
if(ch=='(' || ch=='{' || ch=='[')
st.push(ch);
else{
if(ch==')' && (st.empty()||st.peek()!='('))
return false;
if(ch=='}' && (st.empty()||st.peek()!='{'))
return false;
if(ch==']' && (st.empty()||st.peek()!='['))
return false;
st.pop();
}
}
//遍历完之后发现st非空
if(!st.empty())
return false;
return true;
}
}