1 回答

TA貢獻1859條經驗 獲得超6個贊
一個更簡潔的替代方案:
刪除具有相鄰匹配項的所有括號,即
"()"
。重復這個直到沒有更多。這讓您只剩下不匹配的括號。
計算
)
字符串中有多少。這是(
您需要添加到開頭的數量。計算
(
字符串中有多少。這是)
您需要添加到最后的數量。
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().
添加回答
舉報