Repository navigation
Expand file tree
/
Copy path014_longest_common_prefix.py
More file actions
73 lines (61 loc) · 1.8 KB
/
Copy path014_longest_common_prefix.py
File metadata and controls
73 lines (61 loc) · 1.8 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
71
72
73
class Solution:
def longestCommonPrefix(self, strs) -> str:
if not strs:
return ""
trie = Trie()
for word in strs:
trie.insert(word)
i = 0
tmp = trie.root
while True:
if len(tmp.nodes) == 1 and tmp.isKey == False:
i += 1
tmp = tmp.nodes[list(tmp.nodes.keys())[0]]
else:
return strs[0][:i]
return strs[0][:i]
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TreeNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
if len(word) == 0:
self.root.isKey = True
tmp = self.root
for i in range(len(word)):
if word[i] not in tmp.nodes:
tmp.nodes[word[i]] = TreeNode()
tmp = tmp.nodes[word[i]]
if i == len(word) - 1:
tmp.isKey = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
tmp = self.root
for i in range(len(word)):
if word[i] not in tmp.nodes:
return False
tmp = tmp.nodes[word[i]]
if i == len(word) - 1 and not tmp.isKey:
return False
return True
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
tmp = self.root
for i in range(len(prefix)):
if prefix[i] not in tmp.nodes:
return False
tmp = tmp.nodes[prefix[i]]
return True
class TreeNode:
def __init__(self):
self.isKey = False
self.nodes = {}