Valid Parentheses in TypeScript

function isValid(s: string): boolean {
    // Stack to store opening brackets
    let stack: string[] = [];
    // Object to map closing brackets to their corresponding opening brackets
    let bracketMap: { [key: string]: string } = {
        ')': '(',
        '}': '{',
        ']': '['
    };

    // Iterate through each character in the string
    for (let char of s) {
        if (char === '(' || char === '{' || char === '[') {
            // If it's an opening bracket, push to the stack
            stack.push(char);
        } else {
            // If it's a closing bracket, check the top of the stack
            if (stack.length === 0 || stack.pop() !== bracketMap[char]) {
                // If stack is empty or brackets don't match, return false
                return false;
            }
        }
    }

    // If stack is empty, all brackets were matched, return true; else return false
    return stack.length === 0;
}

PrevNext