-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonPrefix.py
More file actions
36 lines (30 loc) · 891 Bytes
/
Copy pathLongestCommonPrefix.py
File metadata and controls
36 lines (30 loc) · 891 Bytes
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
# coding: utf-8
"""
Write a function to find the longest common prefix string amongst an array of strings.
"""
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
result = ""
else:
temp = []
min_len = min([len(s) for s in strs])
for i in xrange(min_len):
flag = True
for j in xrange(1, len(strs)):
if strs[0][i] != strs[j][i]:
flag = False
break
if flag:
temp.append(strs[0][i])
else:
break
result = ''.join(temp)
return result
if __name__ == '__main__':
s = Solution()
print s.longestCommonPrefix(['abc', 'ab', 'abcd'])