Skip to content

Instantly share code, notes, and snippets.

@paramire
Last active July 2, 2022 23:02
Show Gist options
  • Select an option

  • Save paramire/855c01d1c7d6218a7a9fce9b4f4b627b to your computer and use it in GitHub Desktop.

Select an option

Save paramire/855c01d1c7d6218a7a9fce9b4f4b627b to your computer and use it in GitHub Desktop.
LongestWord - Issue 254
function longestWord(token, words) {
words = words.sort((a, b) => b.length - a.length);
// after sort find will be the longest
const longestWord = words.find((word) => {
let index = 0;
for (let charIndex = 0; charIndex < word.length; charIndex++) {
if (!token.slice(index).includes(word[charIndex])) {
break;
}
index = token.slice(index).indexOf(word[charIndex]);
if (charIndex + 1 === word.length) return true;
}
return false;
});
return longestWord;
}
let str = "abppplee";
let dict = ["able", "ale", "apple", "bale", "kangaroo"];
longestWord(str, dict);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment