14. longest common prefix

Description

Difficulty: Easy

Write a function to find the longest common prefix string amongst an array of strings.

题意:

给出一 list,内容为一些字符串,找出这些字符串的最长公共前缀。

Solution

先将前缀 prefix 定位 list 的第一个元素。对于之后的每一个元素,如果该元素比 prefix 短,则先将 prefix 切成相应长度。然后对比 prefix 与当前元素,遇到不同则将 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
25
class (object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if strs == []:
return ''
elif len(strs) == 1:
return strs[0]
prefix = strs[0]
for s in strs[1:]:
if s == '' or prefix == '':
return ''
prefix = prefix[:min(len(prefix), len(s))]
for posi in range(len(prefix)):
if prefix[posi] != s[posi]:
prefix = prefix[:posi]
break
if len(prefix) == 0:
return ''
return prefix