您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

在 JavaScript 中查找括号分数

2024/4/17 1:35:29发布5次查看
问题我们需要编写一个 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 中查找括号分数的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录