javascript - Codewars - 平衡括号 - Javascript
问题描述
试图解决这个代码战挑战:
您的工作是修正括号,以便所有左括号和右括号(括号)都有匹配的对应项。您将通过在字符串的开头或结尾附加括号来完成此操作。结果应该是最小长度。不要添加不必要的括号。
输入将是一个可变长度的字符串,仅包含“(”和/或“)”。
例如:
Input: ")(" Output: "()()" Input: "))))(()(" Output: "(((())))(()())"
我的想法是创建一个“堆栈”,然后在遇到“相反”括号时将该堆栈推入最终数组。
const fixParentheses = (str) => {
let array = Array.from(str);
let final = [];
let stack = [];
for (let j = 0; j < array.length; j++) {
if (array[j] === ')' && array[j + 1] === ')'){
stack.push(')');
}
if (array[j] === ')' && array[j + 1] === '(') {
stack.push(')');
stack.unshift('('.repeat(stack.length));
stack = stack.join();
stack = stack.replace(/[,]/gi, '');
final.push(stack);
stack = [];
}
if (array[j] === '(' && array[j + 1] === '(') {
stack.push('(');
}
if (array[j] === '(' && array[j + 1] === ')') {
stack.push('(');
stack.push(')'.repeat(stack.length));
stack = stack.join();
stack = stack.replace(/[,]/gi, '');
final.push(stack);
stack = [];
}
}
return final.join('');
}
console.log(fixParentheses('))))(()('));
期望的输出:'(((())))(()())'
问题是这是平衡的,但顺序不正确。
我不知道如何解释我们看到的情况(()(
,而函数不会变得太复杂(它已经是)。
另外,您能否向我解释一下为什么我目前必须将数组方法分开在不同的行上?即为什么
stack.push('(');
stack.push(')').repeat(stack.length));
stack = stack.join();
stack = stack.replace(/[,]/gi, '');
不会产生错误,但是stack.push('(').push(')'.repeat(stack.length)).join().replace(/[,]/gi, '');
呢?我想优化。
解决方案
更简洁的替代方案:
- 删除具有相邻匹配项的所有括号,即
"()"
. - 重复此操作,直到没有更多。这使您只剩下不匹配的括号。
)
数一数你在字符串中有多少。这是(
您需要添加到开头的数量。(
数一数你在字符串中有多少。这是)
您需要添加到最后的数量。
const fixParentheses = (str) => {
let orig = str;
//Repeatedly remove all instances of "()" until there are none left
while (str.includes("()"))
str = str.replace(/\(\)/g, '');
//Count the number of ")" and "(" left in the string
let amtOpeningParensNeeded = (str.match(/\)/g) || []).length;
let amtClosingParensNeeded = (str.match(/\(/g) || []).length;
//Add that many "(" and ")" to the string, respectively
return "(".repeat(amtOpeningParensNeeded) + orig + ")".repeat(amtClosingParensNeeded);
};
//You can ignore this, it's just a wrapper for demo/logging purposes
const test = input => { console.log(`Input: ${input}`); console.log(`Output: ${fixParentheses(input)}`)};
test(")(");
test("))))(()(");
为什么我必须将我的数组方法分成新行?为什么会
stack.push('(').push(')'.repeat(stack.length)).join().replace(/[,]/gi, '');
抛出错误?
您不能将其他 Array 方法链接到,.push()
因为它不返回 Array;它返回一个表示新数组的整数length
。
出于所有意图和目的,["apples","oranges"].push("banana").join()
与做3.join()
.
推荐阅读
- angular - 反应式表单父组件将数据传递给子组件
- reactjs - 在redux中按下重置按钮时如何初始化所有状态
- python - 将滚动平均值应用于列时如何填充第一个 N/A 单元格-python
- svn - 来自特定版本的 SVN 分叉
- node.js - 使用节点验证 Auth0 JWT
- angular - Angular navigation issue (router.navigate)
- regex - 正则表达式验证 2 个字符和“-”以及 8 位数字
- android - 我们可以根据需要调整原生广告的大小吗?
- javascript - 消除
- 基于页面加载日期
- python - python - 将列表与 csv 进行比较