Skip to content

Instantly share code, notes, and snippets.

@lumie31
Created June 28, 2022 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lumie31/48a140b7fbd68f2026be8f4d3d179ca2 to your computer and use it in GitHub Desktop.
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.
// 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