Advertisement
Guest User

Untitled

a guest
May 21st, 2019
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. class TreeNode:
  2. def __init__(self, val):
  3. self.val = val
  4. self.counter = 1
  5. self.children = []
  6.  
  7. class Solution:
  8. # @param A : list of strings
  9. # @return a list of strings
  10. def prefix(self, A):
  11. head = TreeNode('')
  12. head.counter = 0
  13.  
  14. for s in A:
  15. n = head
  16. for i in range(len(s)):
  17. found = False
  18. for child in n.children:
  19. if child.val == s[:i+1]:
  20. found = True
  21. n = child
  22. n.counter += 1
  23. break
  24. if not found:
  25. newChild = TreeNode(s[:i+1])
  26. n.children.append(newChild)
  27. n = newChild
  28.  
  29. stack = [head]
  30. result = []
  31. while stack:
  32. node = stack.pop()
  33. if node.counter == 1:
  34. result.append(node.val)
  35. else:
  36. for child in node.children:
  37. stack.append(child)
  38.  
  39. return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement