Home  >  Article  >  Web Front-end  >  Find bracket fractions in JavaScript

Find bracket fractions in JavaScript

WBOY
WBOYforward
2023-09-01 18:17:081063browse

在 JavaScript 中查找括号分数

Question

We need to write a JavaScript function that accepts a balanced square bracket string str as the first and only parameter.

Our function should calculate and return the score of the string according to the following rules -

  • [] has a score of 1

  • AB has a score of A B, where A and B are balanced bracket strings.
  • [A] has a score of 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

The 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

The above is the detailed content of Find bracket fractions in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete