014 longest common prefix

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

思路

注意,参数strs是一个string类型的数组。思路很直白,从数组中每一个字符串的起始位置开始搜索并依次进行比较。只要有其中一个字符串在该位置的字符与其它的字符串不同,搜索结束,从而得到字符串数组的最长公共前缀。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class (object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
length = len(strs)
if (length == 0):
return ''
else:
pos = 0
res = ''
while(True):
for i in range(length):
if (pos >= len(strs[i])):
return res
else:
if (strs[i][pos] != strs[0][pos]):
return res
res += strs[0][pos]
pos += 1