LintCode_chapter1_section6_longest-common-prefix

coding = utf-8

'''
Created on 2015年11月6日

@author: SphinxW
'''
# 最长公共前缀
#
# 给k个字符串,求出他们的最长公共前缀(LCP)
# 您在真实的面试中是否遇到过这个题?
# 样例
#
# 在 "ABCD" "ABEF" 和 "ACEF" 中,  LCP 为 "A"
#
# 在 "ABCDEFG", "ABCEFG", "ABCEFA" 中, LCP 为 "ABC"


class Solution:
    # @param strs: A list of strings
    # @return: The longest common prefix

    def longestCommonPrefix(self, strs):
        # write your code here
        maxLength = 0
        shortWord = None
        for word in strs:
            thisLength = len(word)
            if thisLength > maxLength:
                maxLength = thisLength
                shortWord = word
        for length in range(1, maxLength + 1)[::-1]:
            flag = False
            head = shortWord[:length]
            for word in strs:
                if not word[:length] == head:
                    flag = False
                    break
                flag = True
            if flag:
                return head
        return ""
s = Solution()
print(s.longestCommonPrefix((["AABCD", "AABEF", "AACEF"])))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容