LintCode_chapter1_section5_longest-common-substring

coding = utf-8

    '''
    Created on 2015年11月6日
    
    @author: SphinxW
    '''
    # 长公共子串
    #
    # 给出两个字符串,找到最长公共子串,并返回其长度。
    #
    #
    # 您在真实的面试中是否遇到过这个题?
    # 样例
    #
    # 给出A=“ABCD”,B=“CBCE”,返回 2
    # 注意
    #
    # 子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
    
    
    class Solution:
        # @param A, B: Two string.
        # @return: the length of the longest common substring.
    
        def longestCommonSubstring(self, A, B):
            if len(B) == 0:
                return 0
            # write your code here
            for length in range(1, len(B) + 1)[::-1]:
                for index in range(len(B) - length + 1):
                    if A.find(B[index:index + length]) == -1:
                        pass
                    else:
                        return length
            return 0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容