-
-
Save lumie31/48a140b7fbd68f2026be8f4d3d179ca2 to your computer and use it in GitHub Desktop.
Given a string str and a set of words dict, find the longest word in dict that is a subsequence of str.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// function to determine if a word is subsequence to another | |
const isSubsequence = (s, t) => { | |
let i = 0, j = 0; | |
while (i < s.length && j < t.length) { | |
if (s[i] === t[j]) { | |
i++; | |
} | |
j++; | |
} | |
return i === s.length | |
}; | |
const longestWord = (str, dict) => { | |
let longest = 0, result = ''; | |
for (let word of dict) { | |
if (isSubsequence(word, str) && word.length > longest) { | |
longest = word.length; | |
result = word; | |
} | |
} | |
return result | |
} | |
// longestWord("abppplee", ["able", "ale", "apple", "bale", "kangaroo"]) --> "apple" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment