Advertisement
FreyasSpirit

Untitled

Nov 3rd, 2020
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. class Solution(object):
  2. # Hack to remove an element from a list and make a copy.
  3. # There's probably a way better way to do this.
  4. def removeAndReturnList(self, words, toRemove):
  5. wordsCopy = words[:]
  6. wordsCopy.remove(toRemove)
  7. return wordsCopy
  8.  
  9. # Dynamic programming solution based on the recursive solution
  10. def findSubstring(self, s, words):
  11. """
  12. :type s: str
  13. :type words: List[str]
  14. :rtype: List[int]
  15. """
  16.  
  17. # Lengths of all words
  18. wordLen = len(words[0])
  19.  
  20. # The last [wordLen] of these are the base case
  21. # In all other cases, we need this anyway so initialize it now
  22. # We could sort this first to bring this from O(mn^2) to O(mnlogn)
  23. wordLists = [[words] for i in range(len(s) + 1)]
  24.  
  25. for i in range(len(s), wordLen-1, -1):
  26. substr = s[i-wordLen : i] # The wordLen substr starting i from the end
  27. for wordList in wordLists[i]:
  28. # Here's where the sorting would help
  29. if substr in wordList:
  30. wordLists[i-wordLen].append(self.removeAndReturnList(wordList, substr))
  31.  
  32.  
  33. out = []
  34. # Characters where empty lists exist are the solution
  35. for i in range(len(wordLists)):
  36. for words in wordLists[i]:
  37. if not words:
  38. out.append(i)
  39.  
  40. return out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement