lc14-Longest Common Prefix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
leng=len(strs[0])
shortest_index=0
if len(strs) == 1:
return strs[0]
#find shortest
for i,str in enumerate(strs):
if len(str)<leng:
shortest_index=i
leng=len(str)
pref=strs[shortest_index]
#find most common prefix
for str in strs:
while str.startswith(pref) == False:
leng-=1
pref=pref[:leng]
return pref