// 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
max_breadth code does not work for all cases.
max_breadth function does not work for valid paraentheses expressions like
"(())(())(())()()" breadth is 3 here and "(()()()) ,((()())(())(()())(()()()))" breadth is 4 here