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.
class Solution { public boolean isValid(String s) { Stacktag = new Stack<>(); try { for (char c : s.toCharArray()) { switch (c) { case '(': tag.push(')'); break; case ')': if (c != tag.pop()) return false; break; case '[': tag.push(']'); break; case ']': if (c != tag.pop()) return false; break; case '{': tag.push('}'); break; case '}': if (c != tag.pop()) return false; break; default: break; } } } catch (Exception e) { return false; } return tag.empty(); }}