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.
tag:
- String
- stack
java
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
String left = "([{", right = ")]}";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
stack.push(s.charAt(i));
} else {
if (stack.isEmpty() || s.charAt(i) != right.charAt(left.indexOf(stack.peek())))
return false;
stack.pop();
}
}
if (!stack.isEmpty())
return false;
return true;
}