Home > Web Front-end > JS Tutorial > body text

Find bracket fractions in JavaScript

WBOY
Release: 2023-09-01 18:17:08
forward
1090 people have browsed it

在 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 = '[][]';
Copy after login

output

const output = 2;
Copy after login

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));
Copy after login

Output

2
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!