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.
Difficulty: Easy
public class Solution {
public boolean isValid(String s) {
int len = s.length();
if(len%2 == 1)
return false;
HashMap<Character, Character> hm = new HashMap<Character, Character>();
hm.put('(', ')');
hm.put('[', ']');
hm.put('{', '}');
Stack<Character> st = new Stack<Character>();
for(int i = 0; i < len; i++){
if(st.empty()){
st.push(s.charAt(i));
}
else{
if(hm.containsKey(st.peek()) && hm.get(st.peek()) == s.charAt(i)){
st.pop();
}
else{
st.push(s.charAt(i));
}
}
}
return st.empty();
}
}