gpt4 book ai didi

javascript - 如何在没有hashmap的情况下找到字符串中第一对重复的单词?

转载 作者:行者123 更新时间:2023-11-29 20:30:46 25 4
gpt4 key购买 nike

我试图在字符串中找到第一对重复的单词,但我只能按照句子中第一个单词的顺序找到所有重复的对,而不是第一对。例如在字符串“I love my anthony so much with all my hearts love”中,输出应该是我的,但它给了我爱。

let Sentence = 'I love my anthony so much with all my hearts love';

function wordRepeat(str) {
let splitStr = str.split(' ');
let list = [];

for (let i = 0; i < splitStr.length; i++) {
for (let j = i + 1; j < splitStr.length; j++) {
if (splitStr[i].match(splitStr[j])) {
//repeat = splitStr[i];
list.push(splitStr[i]);
}
}
}
//console.log(list);
return list[0];
}

console.log(wordRepeat(Sentence));

输出应该是'my',但我得到'love',但是'my'是正确答案,因为它是第一对。

最佳答案

你可以这样使用:

function getDuplicate(inString){
const arr=inString.split(/\W+/g);// This is a Regular Expression - See it in use at https://regex101.com/r/X0Cyxx/1
return arr.find( (word,index) =>
arr.slice(0,index).includes(word)
);
}

EDIT: I modified line 2 to include punctuation, as @Phil suggested. Thanks, @Phil!

关于javascript - 如何在没有hashmap的情况下找到字符串中第一对重复的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58422823/

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