在 JavaScript 中查找括号分数
问题
我们需要编写一个 JavaScript 函数,它接受一个平衡的方括号字符串 str 作为第一个也是唯一的参数。
我们的函数应该根据以下规则计算并返回字符串的分数 -
[] 得分 1
AB 的分数为 A + B,其中 A 和 B 是平衡括号字符串。
[A] 的分数为 2 * A,其中 A 是平衡括号字符串。
例如,如果函数的输入是
输入
const str = '[][]';
输出
const output = 2;
示例
以下是代码 -
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));
输出
2
以上是 在 JavaScript 中查找括号分数 的全部内容, 来源链接: utcz.com/z/335561.html
