In: Computer Science
function isValidString(s) {
var count = 0;
for (let c of s) { // check for equal number of brackets
if (c === '(') {
count++;
}
else if (c === ')') {
count--;
}
if (count < 0) return false;
}
return count === 0; // return true if no extra brackets
}
function balance(s) {
let levels = [s]; // create array
while (true) { // run till condition is true
let valid = levels.filter(isValidString) ; // return string
according to given condition
if (valid.length > 0) { // check length must be greater than
0
return new Set(valid);
}
// check validity of all possible substrings with one
character removed.
let nextlevels = [];
for (let s of levels) {
for (let i = 0; i < s.length; i++) {
nextlevels.push(s.substring(0, i) + s.substring(i + 1));
}
}
levels = nextlevels;
}
}
console.log(balance('()()'));
console.log(balance('())'));
console.log(balance('a(b)c'));
console.log(balance('a(b)c())'));