Created
December 15, 2015 16:07
-
-
Save ramhiser/969787f85b8306e6c984 to your computer and use it in GitHub Desktop.
Python snippet to remove any substrings of other strings in the list
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
from collections import defaultdict | |
def remove_substrings(words): | |
"""Remove any substrings of other strings in the list. | |
O(n) solution from... | |
Source: http://stackoverflow.com/a/24049808/234233 | |
""" | |
longest = defaultdict(str) | |
for word in words: # O(n) | |
for i in range(1, len(word) + 1): # O(k) | |
for j in range(len(word) - i + 1): # O(k) | |
subword = word[j:j + i] # O(1) | |
if len(longest[subword]) < len(word): # O(1) | |
longest[subword] = word # O(1) | |
filtered_list = list(set(longest.values())) | |
# Keep original order | |
filtered_list = [s for s in words if s in filtered_list] | |
return filtered_list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment