Short JAVA solution using ASCII difference


  • 0
    S

    Look into ASCII. Difference between '(' and ')' is 1. Difference between '{' and '}', '[' and ']' is 2.

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        
        for (int i = 0; i < s.length(); i++){
            char parenthese = s.charAt(i);
            if (parenthese == ')' || parenthese == '}' || parenthese == ']'){
                if (stack.empty()) return false;
                if (stack.peek() + 1 == parenthese || stack.peek() + 2 == parenthese) stack.pop();
                else return false;
            }
            else stack.push(parenthese);
        }
        
        return stack.empty();
    }

Log in to reply
 

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