LeetCode - Longest Common Prefix

来源:互联网 发布:c#面试算法题 编辑:程序博客网 时间:2024/05/17 22:38

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

注意做好对特殊情况的考虑即可。

0 0
原创粉丝点击