File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ from collections import defaultdict
2+
3+
4+ class TrieNode(object):
5+ def __init__(self):
6+ """
7+ Initialize your data structure here.
8+ """
9+ self.nodes = defaultdict(TrieNode) # Easy to insert new node.
10+ self.isword = False # True for the end of the trie.
11+
12+
13+ class Trie(object):
14+ def __init__(self):
15+ self.root = TrieNode()
16+
17+ def insert(self, word):
18+ """
19+ Inserts a word into the trie.
20+ :type word: str
21+ :rtype: void
22+ """
23+ curr = self.root
24+ for char in word:
25+ curr = curr.nodes[char]
26+ curr.isword = True
27+
28+ def search(self, word):
29+ """
30+ Returns if the word is in the trie.
31+ :type word: str
32+ :rtype: bool
33+ """
34+ curr = self.root
35+ for char in word:
36+ if char not in curr.nodes:
37+ return False
38+ curr = curr.nodes[char]
39+ return curr.isword
40+
41+ def startsWith(self, prefix):
42+ """
43+ Returns if there is any word in the trie
44+ that starts with the given prefix.
45+ :type prefix: str
46+ :rtype: bool
47+ """
48+ curr = self.root
49+ for char in prefix:
50+ if char not in curr.nodes:
51+ return False
52+ curr = curr.nodes[char]
53+ return True
Original file line number Diff line number Diff line change 1+ class TrieNode :
2+ def __init__ (self ):
3+ self .children = {}
4+ self .end = False
5+
6+ class Trie :
7+ def __init__ (self ):
8+ self .root = TrieNode ()
9+
10+ def insert (self , word ):
11+ cur = self .root
12+ for c in word :
13+ if c not in cur .children :
14+ cur .children [c ] = TrieNode ()
15+ cur = cur .children [c ]
16+ cur .end = True
17+
18+ def longest_word (self ):
19+ def helper (node , partial_res ):
20+ res = partial_res
21+ for c , child in node .children .items ():
22+ if child .end :
23+ pot = helper (child , partial_res + c )
24+ if len (pot ) > len (res ):
25+ res = pot
26+ elif len (pot ) == len (res ) and pot < res :
27+ res = pot
28+ return res
29+ return helper (self .root , '' )
30+
31+ class Solution :
32+ def longestWord (self , words ):
33+ """
34+ :type words: List[str]
35+ :rtype: str
36+ """
37+ T = Trie ()
38+ for word in words :
39+ T .insert (word )
40+ return T .longest_word ()
41+
42+
43+ ½â· ¨¶þ :
44+ class Solution (object ):
45+ def longestWord (self , words ):
46+ """
47+ :type words: List[str]
48+ :rtype: str
49+ """
50+ words .sort ()
51+ words_set , longest_word = set (['' ]), ''
52+ for word in words :
53+ if word [:- 1 ] in words_set :
54+ words_set .add (word )
55+ if len (word ) > len (longest_word ):
56+ longest_word = word
57+ return longest_word
You can’t perform that action at this time.
0 commit comments