字母数:返回重复字母数最多的第一个单词 [英] Letter Count: return the first word with the greatest number of repeated letters
问题描述
任何人都可以帮我解决这个问题吗?这是一个字母计数挑战,您需要返回具有最大重复字母数的第一个单词,例如:Input =Hello apple pie输出= Hello
Can anyone help me out with the bug? This is a letter count challenge that you need to return the first word with greatest number of repeated letters, e.g.: Input = "Hello apple pie" Output = Hello
我试过了调试我的代码的许多不同方法,并注意到字符串没有传递到while循环,但我不知道为什么。任何人都可以解释一下吗?
I tried many different ways to debug my code and notice that the string didn't pass into the while loop, but I have no ideas why. Can anyone explain?
function LetterCount(str) {
str = str.split(" ");
var index = 0;
while(index >= str.length){
for(var i = 0; i < str.length; i++){
var str1 = str[i].split("").sort();
for(var k = 0; k < str1.length; k++){
if(index === 0 && str1[k] === str[k+1]){
return str[i];
}
else if(index > 0 && str1[k] === str[k+1]){
return str[i];
}
}
}
index++;
}
return -1;
}
推荐答案
这也是一些正则表达式的魔法。 ;)
Here's some regex magic to pull it off as well. ;)
function LetterCount(str) {
var parts = str.replace(/(\s+)|([A-Z]*?)([A-Z])(\3+)([A-Z]*)|([A-Z]+)/gi, "$1$2$3$4$5$6,$3$4,").split(',');
var firstIndexOfMaxLetters, maxCount = 0;
for (var i = 1; i < parts.length; i += 2)
if (parts[i].length > maxCount)
{ maxCount = parts[i].length; firstIndexOfMaxLetters = i; }
return firstIndexOfMaxLetters ? parts[firstIndexOfMaxLetters-1] : "";
}
LetterCount("Hi apPple pie")
输出:apPple
正则表达式将字符串转换为:
The regex turns the string into this:
["Hi", "", " ", "", "apPple", "pPp", " ", "", "pie", ""]
...其中数组中的每秒项都是重复的字母(如果有的话,否则为空白),以及这个词在它之前。 ;)
... where every second item in the array is the repeating letters (if any, or blank otherwise), and the word is before it. ;)
这篇关于字母数:返回重复字母数最多的第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!