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) {
if (s == null || s.length() == 0) {
return false;
}
int len = s.length();
char[] stack = new char[len];
int top = 0;
for (int i = 0; i < len; ++i) {
char ch = s.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack[top++] = ch;
} else {
if (top == 0) {
return false;
}
char c = stack[--top];
if (c == '(' && ch == ')' || c == '[' && ch == ']' || c == '{' && ch == '}') {
continue;
} else {
return false;
}
}
}
return top == 0;
}
}