SHARE
TWEET

Untitled

a guest May 21st, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.        
  30.         result = []
  31.        
  32.         for s in A:
  33.             n = head
  34.             i = 0
  35.             found = False
  36.             while i < len(s) and not found:
  37.                 for child in n.children:
  38.                     if child.val == s[:i+1]:
  39.                         n = child
  40.                         if n.counter == 1:
  41.                             result.append(s[:i+1])
  42.                             found = True
  43.                 i += 1
  44.        
  45.         return result
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top