Find Largest Word in Dictionary
by Erick Petrucelli
TypeScript
function findLongestWord(input, dictionary) {
dictionary = dictionary.sort((a, b) => b.length - a.length || a.localeCompare(b))
for (let word of dictionary) {
let i = 0, j = 0;
while (i < input.length && j < word.length) {
if (input.charAt(i) === word.charAt(j)) {
i++;
j++;
} else {
i++;
}
}
if (j === word.length) return word;
}
return ""
}
function log(input, expected) {
document.write(
`<pre>${input}: <b>${JSON.stringify(findLongestWord(...input))}</b> <small>// ${expected}</small></pre>`,
)
}
log(["abpcplea", ["ale", "apple", "monkey", "plea"]], "apple")
log(["abpcplea", ["c", "a", "b"]], "a")
log(["bamccore", ["amora", "amor", "amarias"]], "amor")