-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0720_longest_word_in_dictionary.py
More file actions
70 lines (55 loc) · 1.76 KB
/
0720_longest_word_in_dictionary.py
File metadata and controls
70 lines (55 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import unittest
# import collections
class SolutionLeet(object):
def longestWord(self, words):
words_set = set['']
longest_word = ''
words.sort()
for word in words:
if word[:-1] in words_set:
words_set.add(word)
if len(word) > len(longest_word):
longest_word = word
return longest_word
class TrieNode:
def __init__(self, c):
# self.children=collections.defaultdict(TrieNode)
self.children = dict()
self.isWord = False
self.word = ''
class Trie:
def __init__(self):
self.root = TrieNode(None)
def insert(self, word):
current = self.root
for c in word:
if c not in current.children:
current.children[c] = TrieNode(c)
current = current.children[c]
current.isWord = True
current.word = word
def bfs(self):
# q = collections.deque([self.root])
q = [self.root]
res = ''
while q:
cur = q.pop(0)
for n in cur.children.values():
if n.isWord:
q.append(n)
if len(n.word) > len(res) or n.word < res:
res = n.word
return res
class Solution2(object):
def longestWord(self, words):
t = Trie()
for w in words:
t.insert(w)
return t.bfs()
class TestSolution1(unittest.TestCase):
def test_simple(self):
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
self.assertEqual(Solution().longestWord(words), "apple", "solution 1")
self.assertEqual(Solution2().longestWord(words), "apple", "solution 2")
if __name__ == "__main__":
unittest.main()