Jenny
Jenny

Reputation: 494

Javascript Function that removes brackets until only correctly matched brackets are left

I want to write a function that displays the number of brackets that have to be removed until only correctly matched brackets '()' are left. For instance:

Input: "(())()((("
Output: 3

Input: "()(("
Output: 2

My try:

function brackets(para) {

    let array = para.split(' ');

    while(!(array.includes('(')) && !(array.includes(')'))) {
           for(let i=0; i++) {
               if((array[i] === '(') && (array[i+1] === ')')) {
                       array.splice([i+1], 1)
                       array.splice([i], 1)
               }
           }
     } 
     return array.length
}

My main idea was deleting correctly matched brackets '()' out of the array until only ill-matched brackets are left.

I am aware that my for-loop is missing an upper limit, yet didn't know who to correctly implement it. I was wondering if my code could be tweaked in such a way that it still works.

Thanks for reading or even helping me out!

Upvotes: 1

Views: 41

Answers (1)

Yousaf
Yousaf

Reputation: 29282

You could just count the number of opening and closing brackets and return their difference

function brackets(para) {
  let openingCount = 0;
  let closingCount = 0;

  for (let i = 0; i < para.length; i++) {
    if (para[i] == '(')      openingCount++;
    else if (para[i] == ')') closingCount++;
  }

  return Math.abs(openingCount - closingCount);
}

const input = '(())()(((';
const input2 = '()((';

console.log(input + ' ---> ' + brackets(input));
console.log(input2 + '      ---> ' + brackets(input2));

Upvotes: 2

Related Questions