-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path14. Longest Common Prefix.py
More file actions
58 lines (44 loc) · 1.37 KB
/
14. Longest Common Prefix.py
File metadata and controls
58 lines (44 loc) · 1.37 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
from typing import List
class Node:
def __init__(self):
self.children = {}
self.isEnd = False
class TrieSolution:
def __init__(self):
self.result = ""
self.root = Node()
def insertIntoTrie(self,word: str):
cur = self.root
for ch in word:
if ch in cur.children:
cur = cur.children[ch]
continue
else: cur.children[ch] = Node()
cur = cur.children[ch]
cur.isEnd = True
def longestCommonPrefix(self, strs: List[str]) -> str:
for word in strs:
if word == "": return ""
self.insertIntoTrie(word)
# Traverse trie root and find answer
cur = self.root
while len(cur.children) == 1:
val = list(cur.children)[0]
if cur.isEnd: break
self.result += val
cur = cur.children[val]
return self.result
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
result = ""
cur = ""
minStr = 200
for s in strs:
minStr = min(minStr,len(s))
for i in range(minStr):
cur = strs[0][i]
for word in strs:
if word[i] != cur:
return result
result = result + cur
return result