Finding score of brackets in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a balanced square bracket string, str, as the first and the only argument.

Our function should compute and return the score of the string based on the following rule −

  • [] has score 1

  • AB has a score A + B, where A and B are balanced bracket strings.

  • [A] has score 2 * A, where A is a balanced bracket string.

For example, if the input to the function is

Input

const str = '[][]';

Output

const output = 2;

Example

Following is the code −

const findScore = (str = '') => {
   const arr = []
   for(const char of str) {
      arr.push(char)
      while(arr[arr.length - 1] === ']') {
         arr.pop()
         if(arr[arr.length - 1] === '[') {
            arr.pop() arr.push(1)
         } else {
            let num = arr.pop()
            while(arr[arr.length - 1] >= 1) {
               num += arr.pop()
            }
            arr.pop()
            arr.push(2 * num)
         }
      }      
   }
   return arr.reduce((acc, a) => acc + a, 0)
};
console.log(findScore(str));

output

2
raja
Published on 24-Apr-2021 09:41:06
Advertisements