生物信息学与算法Leetcode架构算法设计模式和编程理论

Leetcode 14. Longest Common Pref

2018-03-21  本文已影响12人  Zentopia

Python 3 实现:

源代码已上传 Github,持续更新。

"""
14. Longest Common Prefix

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

class Solution:

    def longestCommonPrefix(self, strs):
        """
        :type strs: List[str]
        :rtype: str
        """

        if len(strs) == 0:
            return ''

        result = strs[0]

        for str in strs:
            result = self.commonPrefix(result, str)
        return result

    def commonPrefix(self, str, str1):
        commonPrefix = ''
        size = len(str) if len(str) <= len(str1) else len(str1)
        for i in range(size):
            if str[i] == str1[i]:
                commonPrefix = commonPrefix + str[i]
            else:
                break
        return commonPrefix


if __name__ == '__main__':
    solution = Solution()
    strs = ['abcdee', 'abcde', 'abcd']
    print(solution.longestCommonPrefix(strs))
上一篇下一篇

猜你喜欢

热点阅读