-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path014_CommonPrefix.py
52 lines (47 loc) · 1.48 KB
/
014_CommonPrefix.py
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
#Method from others : https://discuss.leetcode.com/topic/6308/simple-python-solution/2
#13.88%
class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if not strs:
return ""
for i, letter_group in enumerate(zip(*strs)):
if len(set(letter_group)) > 1:
return strs[0][:i]
else:
return min(strs)
#Another method from others: https://discuss.leetcode.com/topic/6308/simple-python-solution/2
#57.73%
class Solution:
# @return a string
def longestCommonPrefix(self, strs):
def lcp(s, t):
if len(s)>len(t):
s, t = t, s
for i in range(len(s)):
if s[i]!=t[i]:
return s[:i]
return s
return reduce(lcp,strs) if strs else ""
#26.99% (my method. a shame to python. ^_^)
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if len(strs) == 0:
return ""
if len(strs) == 1:
return strs[0]
flag = True
pos = 0
for charFirst in strs[0]:
for str in strs[1:]:
if len(str) <= pos or str[pos] != charFirst:
flag = False
break
if not flag:
break
pos = pos + 1
return strs[0][:pos]