20. Valid Parentheses
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) {
return false;
}
LinkedList<Character> stack = new LinkedList<>();
// adds a dummy element
stack.addLast('#');
for (char c : s.toCharArray()) {
switch (c) {
case '{':
case '[':
case '(':
stack.addLast(c);
break;
case '}':
if (stack.getLast() == '{') {
stack.removeLast();
} else {
return false;
}
break;
case ']':
if (stack.getLast() == '[') {
stack.removeLast();
} else {
return false;
}
break;
case ')':
if (stack.getLast() == '(') {
stack.removeLast();
} else {
return false;
}
break;
default:
break;
}
}
return stack.size() == 1;
}
}