Topic describes

Train of thought

Three situations need to be addressed:

  • Bracket closing types do not match
  • There are left open parentheses that cannot cancel out
  • Uncancelable close parenthesis/close parenthesis first

code

class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put(') '.'(');
        map.put('] '.'[');
        map.put('} '.'{');
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
                stack.push(s.charAt(i));
            } else if(stack.isEmpty() || stack.pop() ! = map.get(s.charAt(i))) {return false;// stack.isempty () applies to the case where a close parenthesis is present first, and the following condition applies to the case where the parenthesis type does not match}}return stack.isEmpty();// For cases where the remaining left parentheses do not cancel out}}Copy the code