My minimal if else and constant space solution


  • 0
    R
    class Solution {
        private static final Map<Character, Character> BRACE_PAIR = new HashMap<>();
    
        static {
            BRACE_PAIR.put('}', '{');
            BRACE_PAIR.put(')', '(');
            BRACE_PAIR.put(']', '[');
        }
    
        public boolean isValid(String s) {
            if (s == null || s.isEmpty()) {
                return true;
            }
            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 (!(BRACE_PAIR.containsKey(s.charAt(i)) && !stack.isEmpty() &&
                        BRACE_PAIR.get(s.charAt(i)) == stack.pop())) {
                    return false;
                }
            }
            return stack.isEmpty();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.