Valid Parentheses

Valid Parentheses

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.

  2. Open brackets must be closed in the correct order.

  3. Every close bracket has a corresponding open bracket of the same type.

LeetCode Problem - 20

class Solution {
    public boolean isValid(String s) {
        // Create a stack to store opening parentheses
        Stack<Character> str = new Stack<>();

        // Iterate through each character in the string
        for (int i = 0; i < s.length(); i++) {
            char currentChar = s.charAt(i);

            // Check if the current character is an opening parenthesis
            if (isOpening(currentChar)) {
                // Push opening parenthesis onto the stack
                str.push(currentChar);
            } else {
                // If stack is empty, return false as there is no matching opening parenthesis
                if (str.isEmpty()) return false;
                // If the current closing parenthesis does not match the top opening parenthesis, return false
                else if (!isMatching(str.peek(), currentChar)) {
                    return false;
                }
                // If the current closing parenthesis matches the top opening parenthesis, pop it from the stack
                else str.pop();
            }
        }

        // If stack is empty, all opening parentheses have been matched, return true
        return str.isEmpty();
    }

    // Method to check if a character is an opening parenthesis
    boolean isOpening(char c) {
        return c == '(' || c == '{' || c == '[';
    }

    // Method to check if two characters form a valid pair of parentheses
    boolean isMatching(char a, char b) {
        return (a == '(' && b == ')') || (a == '{' && b == '}') || (a == '[' && b == ']');
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!