Search code snippets, questions, articles...

Parenthesis Validation, Max Depth and Max Breadth - Braze - Full Stack - 12/20/21

// inputStr: May or may not contain paraentheses 
// valid: (()), check if valid expression
// some string // true
// (some string) // true
// ((some) string // false
// (() ())
// )))
// valid if no unbalanced set of parentheses
function hasValidParens(inputStr) {
    const parens = [];
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            const lastParens = parens.pop()
            if (typeof lastParens == 'undefined') {
                return false; 
            }
        }
    }
    
    return parens.length === 0; 
}


//console.log(hasValidParens("()")); // true
//console.log(hasValidParens("some string")); // true
//console.log(hasValidParens("(some string)")); // true 
//console.log(hasValidParens("((some) string")); // false 
//console.log(hasValidParens("(() ())")); // true
//console.log(hasValidParens(")))")); // false
//console.log(hasValidParens("(((")); // false


// maxDepth: (()) 2 
// ((), ()) 2
// ((), (())) 3
// Assume that it's valid 

function maxDepth(inputStr) {
    const parens = []; 
    let maxDepth = 0; 
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            if (parens.length > maxDepth) {
                maxDepth = parens.length;
            }
            parens.pop()
        }
    }
    
    return maxDepth;
}

//console.log(maxDepth("(())")); // 1
//console.log(maxDepth("((), ())")); // 2
//console.log(maxDepth("((), (()))")); // 2
//console.log(maxDepth("((()), ())")); // 2
// ()()(()()) // 3

// maxBreadth 

function maxBreadth(inputStr) {
    const parens = []; 
    let maxBreadth = 0; 
    
    for (let i = 0; i < inputStr.split('').length; i++) {
        if (inputStr[i] === '(') {
            parens.push('(')
        } else if (inputStr[i] === ')') {
            parens.pop();
            
            if (parens.length === 0) {
                maxBreadth++;
            }
            
        }
    }
    
    return maxBreadth;
}

console.log(maxBreadth("(())")); // 1
console.log(maxBreadth("((), ())")); // 2
console.log(maxBreadth("((), (()))")); // 2
console.log(maxBreadth("((()), ())")); // 2
console.log(maxBreadth("()()(()())")); // 3
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Was this helpful?
0 Comments