Is Valid
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.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
Method:
Be careful for strings that start with closing brackets.
Solution:
Time: O(n)
Space: O(n)
public class Solution {
public int isValid(String A) {
// ()[]{}
Deque<Character> stack = new ArrayDeque<>();
char[] arr = A.toCharArray();
for (char c : arr) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) return 0;
char left = stack.pop();
if (c == ')') {
if (left != '(') {
return 0;
}
} else if (c == ']') {
if (left != '[') {
return 0;
}
} else if (c == '}') {
if (left != '{') {
return 0;
}
}
}
}
if (stack.isEmpty()) {
return 1;
} else {
return 0;
}
}
}