'How to implement count missing brackets?
For example: I have a string only contains brackets '(' and ')'. How to count missing brackets?
My code:
var str = '(())';
var open = 0, close = 0, count = 0;
for (var i = 0; i < str.length; i++) {
if (str[i] == '(') {
open++;
count = Math.abs(open - close);
} else {
close++;
count = Math.abs(open - close);
}
}
console.log(count);
Input: '(())' Output: 0
Input: '(()' Output: 1
Input: '))((' Output: 4
Input: '(()(' Output: 2
Input: '(()()))(())(())' Output: 1
Solution 1:[1]
You could replace perfect brackets and count the rest.
function missing(string) {
var l;
do {
l = string.length;
string = string.replace(/\(\)/g, '');
} while (l !== string.length)
return string.length;
}
console.log(missing('(())')); // 0
console.log(missing('(()')); // 1
console.log(missing('))((')); // 4
console.log(missing('(()(')); // 2
console.log(missing('(()()))(())(())')); // 3
Solution 2:[2]
Below code output missing parenthesis count
var missingParenthesisCnt = function(s) {
var stack = 0, combo=[];
for (var i = 0; i < s.length; i++) {
var item = s[i];
if (s[i]=="(") {
if(stack<0){
combo.push(Math.abs(stack))
stack=0
}
stack+=1
}
else if(s[i]==")"){
stack-=1
}
}
return stack + combo.reduce((a,b)=>a+b, 0);
}
console.log("Total Missing Parenthesis Count:", missingParenthesisCnt(")))((()"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nina Scholz |
| Solution 2 |
