您的位置:首页 > 其它

LeetCode - Longest Common Prefix

2015-04-21 15:17 260 查看

LeetCode - Longest Common Prefix

The problem is described as following:

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

My solution is as following:

class Solution:
# @param {string[]} strs
# @return {string}
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ''
if len(strs) == 1:
return strs[0]
result = ''
for i in range(min(len(strs[0]), len(strs[1]))):
if strs[0][i] == strs[1][i]:
result += strs[0][i]
else:
break
for i in range(2, len(strs)):
j = 0
while j < min(len(result), len(strs[i])):
if result[j] != strs[i][j]:
result = result[0:j]
break
j += 1
result = result[0:j]
return result


注意做好对特殊情况的考虑即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode