首页 > 解决方案 > 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, '');呢?我想优化。

标签: javascriptarraysstring

解决方案


更简洁的替代方案:

  1. 删除具有相邻匹配项的所有括号,即"()".
  2. 重复此操作,直到没有更多。这使您只剩下不匹配的括号。
  3. )数一数你在字符串中有多少。这是(您需要添加到开头的数量。
  4. (数一数你在字符串中有多少。这是)您需要添加到最后的数量。

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().


推荐阅读