Stack
Valid Parentheses
class Solution {
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put(')', '(');
map.put('}', '{');
map.put(']', '[');
Stack<Character> stack = new Stack<>();
int n = s.length();
for (int i = 0; i < n; i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
char topChar = stack.isEmpty() ? '#' : stack.pop();
if (topChar != map.get(c)) return false;
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}Simplify Path
Last updated