Advertisement
kosievdmerwe

472.

Jan 27th, 2023
762
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. class Trie:
  2.     __slots__ = ['children', 'word']
  3.  
  4.     def __init__(self):
  5.         self.children = defaultdict(Trie)
  6.         self.word = False
  7.  
  8.     def add(self, word: str) -> None:
  9.         cur = self
  10.         for c in word:
  11.             cur = cur.children[c]
  12.         cur.word = True
  13.    
  14.  
  15. class Solution:
  16.     def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
  17.         trie = Trie()
  18.         for w in words:
  19.             trie.add(w)
  20.        
  21.         ans = []
  22.         for w in words:
  23.             W = len(w)
  24.            
  25.             to_check = [0]
  26.             matched = False
  27.  
  28.             while to_check:
  29.                 i = heappop(to_check)
  30.                 while to_check and to_check[0] == i:
  31.                     heappop(to_check)
  32.  
  33.                 cur_trie = trie
  34.                 for j in range(i, W):
  35.                     if w[j] not in cur_trie.children:
  36.                         break
  37.                    
  38.                     cur_trie = cur_trie.children[w[j]]
  39.  
  40.                     if not cur_trie.word:
  41.                         continue
  42.                    
  43.                     if j == W - 1 and i != 0:
  44.                         matched = True
  45.                     else:
  46.                         heappush(to_check, j + 1)
  47.                    
  48.                 if matched:
  49.                     break
  50.                
  51.             if matched:
  52.                 ans.append(w)
  53.  
  54.         return ans
  55.  
  56.        
  57.  
  58.  
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement