gpt4 book ai didi

javascript - 如何将结果字符串添加到数组中并消除重复项?

转载 作者:行者123 更新时间:2023-12-01 00:44:23 25 4
gpt4 key购买 nike

我对 Javascript 还很陌生,我需要一些帮助来解决 804. 独特的莫尔斯电码单词 - Leetcode 问题。

我想出了如何通过使用单词中每个字母的索引来搜索返回莫尔斯电码,并使用它来连接莫尔斯电码数组中那些特定索引处的代码。问题是我无法将结果存储到 Set 数组中(排除重复项并返回 Set 数组的长度)。

var letters = ["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 morseCode = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."];
var words = ["gin", "zen", "gig", "msg"]
var uniqueMorseRepresentations = function(words) {
for (i = 0; i < words.length; i++) {
let word = words[i];
var result = "";
for (j = 0; j < word.length; j++) {
let letter = word.charAt(j);
let index = letters.indexOf(letter);
result += morseCode[index];
};
console.log(result);
};
};
uniqueMorseRepresentations(words);

console.log 方法以 4 个单独的字符串返回结果,但我不知道如何将它们存储到数组中,同时验证是否存在重复。

如果问题很草率,我很抱歉。这是我的第一个。

提前致谢!

最佳答案

在您的函数中,创建一个集合:

 const resultSet = new Set();

然后,当每个结果建立时(当您记录它时),将生成的莫尔斯电码添加到该集合中:

resultSet.add(result);

然后您最终可以返回该Set或其.size

关于javascript - 如何将结果字符串添加到数组中并消除重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57509957/

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