返回重复字母数最多的第一个单词 [英] Return the first word with the greatest number of repeated letters

查看:147
本文介绍了返回重复字母数最多的第一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是coderbyte易于设置的问题。很多人都问过这个问题,但是我真的很好奇我的解决方案出了什么问题(我知道这是一个非常愚蠢和低效的解决方案。)

原始问题:


让函数LetterCountI(str)取得传入的str参数并返回重复字符数最多的第一个字。例如:今天是有史以来最伟大的一天!应该返回最大,因为它有2个e(和2个t),而且它有2个e的前面。如果没有重复字母的单词返回-1。单词将被空格分开。


我的解决方案大部分时间都在使用。但是,如果看起来输入的最后一个字没有被我的代码所重视。例如,对于a bc ccc,将返回bb而不是ccc。但这里有趣的是,如果字符串只包含一个单词,结果是正确的。例如,ccc返回ccc。



请告诉我我错在哪里。
$ b $ pre $ 函数LetterCountI(str){

str.toLowerCase();

var arr = str.split();

var count = 0;
var word =-1; (var a = 0; a< arr [i] .length; a ++){
$ b $(b
; b $ b var countNew = 0;
for(var b = a + 1; b if(arr [i] [a] === arr [i] [b])
countNew + = 1;
}
if(countNew> count){
count = countNew;
word = arr [i];
}
}
返回字;




$ b

解决方案

我认为问题在于你在最外层循环中放置了 return 语句。

所以你必须把 return 语句在内部循环中。



正确使用 return



  if(countNew> count){
count = countNew;
word = arr [i];
}
返回字;
}
}
}


This is a question from coderbyte’s easy set. Many people asked about it already, but I’m really curious about what’s wrong with my particular solution (I know it’s a pretty dumb and inefficient one..)

Original question:

Have the function LetterCountI(str) take the str parameter being passed and return the first word with the greatest number of repeated letters. For example: "Today, is the greatest day ever!" should return greatest because it has 2 e's (and 2 t's) and it comes before ever which also has 2 e's. If there are no words with repeating letters return -1. Words will be separated by spaces.

My solution works most of the time. But if it seems the last word of the input isn’t valued by my code. For example, for "a bb ccc", "bb" will be returned instead of "ccc". But the funny thing here is if the string only contains one word, the result is correct. For example, "ccc" returns "ccc".

Please tell me where I was wrong. Thank you in advance!

function LetterCountI(str) { 

  str.toLowerCase();

  var arr = str.split(" ");

  var count = 0;
  var word = "-1";

  for (var i = 0; i < arr.length; i++) {
   for (var a = 0; a < arr[i].length; a++) {
     var countNew = 0;
     for (var b = a + 1; b < arr[i].length; b++) {
       if(arr[i][a] === arr[i][b])
          countNew += 1;
     }
     if (countNew > count) {
       count = countNew;
       word = arr[i];
     }
   }
   return word;
  }


}       

解决方案

I think the problem is that you're placing the return statement inside your outermost loop. It should be inside your inner loop.

So you have to place the return statement within the inner loop.

Correct use of return

     if (countNew > count) {
       count = countNew; 
       word = arr[i];
     }
     return word;
    }
  }
} 

这篇关于返回重复字母数最多的第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆