Easy Java Solution


  • 0
    V

    '''
    public boolean isValid(String s) {

        Stack<Character> stack = new Stack<>();
        
        // Iterate through each character of string
        for (int i = 0; i < s.length(); i++) {
            
            // If open brackets, push them onto stack
            if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') stack.push(s.charAt(i));
            else {
                // Check if Stack Size is not 0, if 0 means there was no matching bracket and is unbalanced
                if (stack.size() == 0) return false;
                else {
                    // Pop the current element and compare conditions.
                    char c = stack.pop();
                    if (s.charAt(i) == ')' && c != '(') return false;
                    else if (s.charAt(i) == ']' && c != '[') return false;
                    else if (s.charAt(i) == '}' && c != '{') return false;
            }
        }
    }
    
    // If Stack has something left, unbalanced parantheses.
    if (stack.size() != 0) return false;
    return true;
    }
    

    }


Log in to reply
 

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