Skip to content

Instantly share code, notes, and snippets.

@rvbsanjose
Created April 17, 2014 23:27
Show Gist options
  • Select an option

  • Save rvbsanjose/11017030 to your computer and use it in GitHub Desktop.

Select an option

Save rvbsanjose/11017030 to your computer and use it in GitHub Desktop.
// Using the JavaScript language, have the function LetterCount(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.
// Input = "Hello apple pie" Output = Hello
// Input = "No words" Output = -1
function LetterCount( str ) {
var words = str.split( ' ' );
var longest = 0;
var longest_word;
for ( var i = 0; i < words.length; i++ ) {
var word = words[i];
for ( var j = 0; j < word.length; j++ ) {
var pattern = new RegExp( word[j], 'gi' );
var length = word.match( pattern ).length;
if ( length > 1 && length > longest ) {
longest = word.match( pattern ).length;
longest_word = word;
}
}
}
return longest_word ? longest_word : -1;
}
@abjadify

Copy link
Copy Markdown

Nice solution! One thing I'd watch out for is Unicode. This works well for ASCII text, but once you process languages with different scripts or combining characters, repeated-letter detection becomes a bit more challenging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment