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) {
Stack<Character> st = new Stack<>();
Map<Character, Character> map = new HashMap<Character, Character>();
map.put('(', ')');
map.put('{', '}');
map.put('[', ']');
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(c=='('||c=='{'||c=='['){
st.push(c);
}else {
if(st.empty()){
return false;
}
if(map.get(st.peek())!= c){
return false;
}
else {
st.pop();
}
}
}
return st.empty();
}
}