Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

How to implement count missing brackets?

发布于 2020-03-27 10:27:26

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

Questioner
miyarin
Viewed
22
Michael Beeson 2019-07-03 23:16

In the future it would be best to provide what you have tried so far

But I liked the question and here is a snippet showing it working:

The issue is you need to add to the count of 'missing' when an end bracket appears and there are no start brackets to accompany it.

function countMissing(input) {
  let danglingEnds = 0;
  let opened = 0;
  for (const character of input) {
    if (character === '(') opened++;
    else if (character === ')') {
      if (opened === 0) danglingEnds++;
      else opened--;
    }
  }
  return opened + danglingEnds;
}

console.log(countMissing('(())'));
console.log(countMissing('(()'));
console.log(countMissing('))(('));
console.log(countMissing('(()('));
console.log(countMissing('(()()))(())(())'));