Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created June 27, 2022 11:00
Show Gist options
  • Save les-peters/8cc6a0130fb2a0fd47315f1b938a6b5c to your computer and use it in GitHub Desktop.
Save les-peters/8cc6a0130fb2a0fd47315f1b938a6b5c to your computer and use it in GitHub Desktop.
Longest Word
question = """
Given a string str and a set of words dict, find the longest word in dict that is a subsequence of str.
Example:
let str = "abppplee"
let dict = {"able", "ale", "apple", "bale", "kangaroo"}
$ longestWord(str, dict)
$ 'apple'
// "able" and "ale" also work, but are shorter than "apple"
// "bale" has all the right letters, but not in the right order
"""
import re
def longestWord(str, dictionary):
longest_word = ''
for word in dictionary:
word_pattern = ''
for letter in word:
word_pattern = word_pattern + letter + ".*"
word_p = re.compile(word_pattern)
word_m = word_p.search(str)
if word_m:
if len(word) > len(longest_word):
longest_word = word
return longest_word
str = 'abppplee'
dictionary = ["able", "ale", "apple", "bale", "kangaroo"]
print(longestWord(str, dictionary))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment