gpt4 book ai didi

javascript - 查找数组中重复字符的唯一索引

转载 作者:行者123 更新时间:2023-11-28 03:38:27 25 4
gpt4 key购买 nike

我正在循环遍历一个字符串数组及其字符,以将它们的索引与另一个字符数组进行比较。该代码一直有效,直到字符串具有重复字符 - 然后它仅返回第一个(重复)字符的索引。例如:[“IAMDEFANDJKL”] 对于“A”和“D”,循环仅返回每次出现的第一个索引。

例如:[“abode”]返回[1,2,4,5],然后在应用.length之后返回[4] - 所以[“IAMDEFANDJKL”]应该返回[4,5,6,10,11 ,12] 然后返回 [6](当前返回 [7],因为“D”出现两次)

如何编辑代码以返回所有字符的唯一索引?

function solve() {  
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'];
var testArray = ["IAMDEFANDJKL","thedefgh","xyzDEFghijabc"];
var countArray = [];

for(var i = 0; i < testArray.length; i++) {
var string = testArray[i];
var newArray = [];

for(var char = 0; char < string.length; char++) {
var character = string.charAt(char);
var characterIndex = string.indexOf(character);

for(var alpha = 0; alpha < alphabet.length; alpha++) {
var alphaString = alphabet[alpha];
var alphaIndex = alphabet.indexOf(alphaString);
var characterUpper = character.toUpperCase();
var alphaStringUpper = alphaString.toUpperCase();

if(characterIndex === alphaIndex && characterUpper ===
alphaStringUpper) {
newArray.push(alphaIndex);
}
var arrayLength = newArray.length;
}
}
countArray.push(arrayLength);
}

return countArray;

};

solve();

最佳答案

您可以使用一个对象并存储最后找到的索引加一以供下一次搜索。

function solve() {
var alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
var testArray = ["IAMDEFANDJKL", "thedefgh", "xyzDEFghijabc"];
var countArray = [];

for (var i = 0; i < testArray.length; i++) {
var string = testArray[i];
var newArray = [],
lastIndex = {};

for (var char = 0; char < string.length; char++) {
var character = string[char];
lastIndex[character] = lastIndex[character] || 0;
var characterIndex = string.indexOf(character, lastIndex[character]);

if (characterIndex !== -1) lastIndex[character] = characterIndex + 1;

for (var alpha = 0; alpha < alphabet.length; alpha++) {
var alphaString = alphabet[alpha];
var alphaIndex = alphabet.indexOf(alphaString);
var characterUpper = character.toUpperCase();
var alphaStringUpper = alphaString.toUpperCase();

if (characterIndex === alphaIndex && characterUpper === alphaStringUpper) {
newArray.push(alphaIndex);
}
var arrayLength = newArray.length;
}
}
countArray.push(arrayLength);
}
return countArray;
}

console.log(solve());

通过检查字符串的相同索引来更短的方法。

function solve() {
var alphabet = 'abcdefghijklmnopqrstuvwxyz',
testArray = ["IAMDEFANDJKL", "thedefgh", "xyzDEFghijabc"],
i, j, count, string,
result = [];

for (var i = 0; i < testArray.length; i++) {
count = 0;
string = testArray[i].toLowerCase();
for (j = 0; j < string.length; j++) {
if (string[j] === alphabet[j]) count++;
}
result.push(count);
}
return result;
}

console.log(solve());

关于javascript - 查找数组中重复字符的唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com