Easy-understanding Java solution using Stack


  • 0
    V
    public boolean isValid(String s) {
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char currentChar = s.charAt(i);
            if (currentChar == '(' ||
                    currentChar == '[' ||
                    currentChar == '{'
                    ) {
                stack.push(String.valueOf(currentChar));
            }
            if (currentChar == ')' ||
                    currentChar == ']' ||
                    currentChar == '}'){
                if (stack.empty() || !pairable(stack.pop(),(String.valueOf(currentChar)))){
                    return false;
                }
            }
        }
        return stack.empty();
    }
    
    private boolean pairable(String a, String b) {
        return (a.equals("(") && b.equals(")")) ||
                (a.equals("[") && b.equals("]")) ||
                (a.equals("{") && b.equals("}"));
    }

  • 0
    T

    You can drop chars into a Stack<Character>: char <-> Character conversion is automatic, called auto-boxiing.


Log in to reply
 

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