亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Codewars - 平衡括號 - Javascript

Codewars - 平衡括號 - Javascript

慕容森 2021-10-29 10:50:46
試圖解決這個代碼戰挑戰:您的工作是修復括號,以便所有左括號和右括號(括號)都有匹配的對應項。您將通過在字符串的開頭或結尾附加括號來完成此操作。結果應該是最小長度。不要添加不必要的括號。輸入將是一個不同長度的字符串,只包含“(”和/或“)”。例如: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, '');呢?我想優化。
查看完整描述

1 回答

?
BIG陽

TA貢獻1859條經驗 獲得超6個贊

一個更簡潔的替代方案:

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


查看完整回答
反對 回復 2021-10-29
  • 1 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號