-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestPrefix.py
More file actions
38 lines (31 loc) · 1.25 KB
/
longestPrefix.py
File metadata and controls
38 lines (31 loc) · 1.25 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
class Solution(object):
def longestCommonPrefix(self, strs):
if strs == None or len(strs) == 0:
return ""
shortestStr = self.getShortestStr(strs)
prefix = self.getLongestPrefix(shortestStr, strs, 0)
return prefix
def getShortestStr(self, strs):
minLengt = len(strs[0])
minStr = strs[0]
for string in strs[1:]:
if len(string) < minLengt:
minLengt = len(string)
minStr = string
return minStr
def getLongestPrefix(self, prefix, strs, fromIdx):
if self.allHavePrefix(prefix, strs, fromIdx):
return prefix
midIdx = len(prefix)//2
leftPrefix = self.getLongestPrefix(prefix[:midIdx], strs, fromIdx)
if len(leftPrefix):
rightPrefix = self.getLongestPrefix(prefix[midIdx:], strs, fromIdx + midIdx)
return leftPrefix + rightPrefix
return leftPrefix;
def allHavePrefix(self, prefix, strs, fromIdx):
for string in strs:
if string.startswith(prefix, fromIdx) == False:
return False
return True
lop = Solution()
print(lop.longestCommonPrefix(["flower","florwe","flowflow"]))