I'm trying to solve the classic Valid Parentheses question on LeetCode.
This is what I did, and it can pass all the test cases:
public boolean isValid(String s) {
Deque<Character> stack = new LinkedList<>();
for (Character c : s.toCharArray()) {
if (c.equals('{') || c.equals('[') || c.equals('(')) {
stack.push(c);
} else {
Character check = stack.isEmpty() ? ' ' : stack.pop();
if (check != (c - 1) && check != (c - 2)) { //***
return false;
}
}
}
return stack.isEmpty();
}
but when I change the line *** into this:
if (!check.equals(c - 1) && !check.equals(c - 2)) {}
Although it can pass the compiler, but it can not return the right answer, not even the simple input like "()".
Normally, shouldn't we are supposed to use equals() rather than == to compare Character?