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 static boolean isValid(String s) {
if (s == null || s.length() <= 1) return false;
Stack<Character> bracket = new Stack<Character>();
bracket.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
bracket.push(s.charAt(i));
} else if (s.charAt(i) == ')' && bracket.size() !=0 && bracket.peek() == '(') {
bracket.pop();
} else if (s.charAt(i) == ']' && bracket.size() !=0 && bracket.peek() == '[') {
bracket.pop();
} else if (s.charAt(i) == '}' && bracket.size() !=0 && bracket.peek() == '{') {
bracket.pop();
} else {
return false;
}
}
if (bracket.size() != 0) return false;
return true;
}
转载请注明出处:http://blog.csdn.net/beiyeqingteng