[英]Avoid replacement of previous letters with string.replace
我正在做一個 CodeWars kata,它根據字母的重復將單詞編碼為左括號或右括號。 這是鏈接。
我的代碼適用於所有測試,但只有一個,當 word 等於“(()”時)。
我想我發現在最后一個“)”上,第一個“(”由於替換匹配而被更改為“)”,從而改變了預期輸出。 有什么辦法可以防止我的輸出發生這種不必要的變化?
const duplicateEncode = (word) => {
let words = word.toLowerCase();
let obj = {};
for (let i of words) {
obj[i] = obj[i] ? obj[i] + 1 : 1;
}
for (let i of words) {
obj[i] === 1
? (words = words.replace(i, "("))
: (words = words.replace(i, ")"));
}
return words;
};
預期輸出
duplicateEncode(" ( ( )")); // )))))(
我的輸出
duplicateEncode(" ( ( )")); // ()))))
不要在整個單詞上使用 String.replace ,您應該直接修改每個字符,或者最好只構造一個新字符串來返回。
const duplicateEncode = (word) => { let words = word.toLowerCase(); let obj = {}; for (let i of words) { obj[i] = obj[i] ? obj[i] + 1 : 1; } let out = ""; for (let i of words) { out += obj[i] === 1 ? "(" : ")"; } return out; }; console.log(duplicateEncode(" ( ( )")); // )))))(
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.