Leetcode 14. Longest Common Prefix

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))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容