[英]Replacing all of the repeated characters in javascript
function duplicateEncode(word){
var i;
var j;
for(i = 0; i < word.length; i++) {
for(j = i + 1; j < word.length; j++) {
if (word[i] == word[j]) {
word = word.replace(/word[i]/gi, ')');
}
else word = word.replace(/word[i]/gi, '(');
};
};
return word;
}
我需要得到(如果字符在單詞和這個中沒有重復)如果是並且這段代碼不起作用,它只會給我我輸入的單詞。
您沒有正確使用正則表達式。 這是基於您的原始代碼的一種可能的解決方案。 如您所知,字符串在 Javascript 中是不可變的,因此我們每次都需要使用您的方法重建字符串。
function duplicateEncode(word){ for(i = 0; i < word.length; i++) { if (word[i] == word[i+1]) { word = word.substring(0,i) + ')' + word.substring(i+1); } else { word = word.substring(0,i) + '(' + word.substring(i+1); } } return word; }
為了避免重建字符串,我們可以將字符存儲在一個數組中,然后在最后將它們連接起來,以提高大字符串的性能。
function duplicateEncode(word){ const newWordArr = []; for(i = 0; i < word.length; i++) { if (word[i] == word[i+1]) { newWordArr.push(')'); } else { newWordArr.push('('); } } return newWordArr.join(''); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.