zoukankan      html  css  js  c++  java
  • Python [习题] 求最长共同子串

    s1 = 'abcdefg'
    s2 = 'defabcdoabcdeftw'
    s3 = '1234a'
    s4 = 'wqweshjkb'
    s5 = 'defabcd'
    s6 = 'j'

    求 s1、s3、s4、s5、s6 分别与 s2 的最长共同子串,分别测试有共同子串和没有共同子串的情况下此函数效率问题。

    s1 = 'abcdefg'
    s2 = 'defabcdoabcdeftw'
    s3 = '1234a'
    s4 = 'wqweshjkb'
    s5 = 'defabcd'
    s6 = 'j'
    
    def findstr(str1,str2):
        '''
        Returns str1 and str2 longest common substring.  2017/10/21 23:30
    
        :param str1: 'abcdefg'
        :param str2: 'defabcd'
        :return: 'abcd'
        '''
        count = 0
        length = len(str1)
        for sublen in range(length,0,-1):
            for start in range(0,length - sublen + 1):
                count += 1
                substr = str1[start:start+sublen]
                if str2.find(substr) > -1:
                    print('count={}  subStringLen:{}'.format(count,sublen))
                    return substr
        else:
            return "'{}' and '{}' do not have a common substring".format(str1,str2)
    
    print(findstr(s1,s2))
    print(findstr(s3,s2))
    print(findstr(s4,s2))
    print(findstr(s5,s2))
    print(findstr(s6,s2))
    

      输出结果:

    count=2  subStringLen:6    #findstr(s1,s2)
    abcdef
    
    count=15  subStringLen:1   #findstr(s3,s2)
    a
    
    count=37  subStringLen:1    #findstr(s4,s2)
    w
    
    count=1  subStringLen:7      #findstr(s5,s2)
    defabcd
    
    'j' and 'defabcdoabcdeftw' do not have a common substring  #findstr(s6,s2)
    

      

    永远不要相信用户的输入,一个健壮的代码往往业务功能块代码很少,而对用户输入的验证代码部分越要更严谨,将用户所有的输入都考虑在内。

  • 相关阅读:
    python 的时间复杂度
    python之进制转换
    进程、线程、协程
    [GO]gtk的windows环境搭建
    [GO]并的爬取捧腹的段子
    [GO]并发的网络爬虫
    [GO]百度贴吧的爬虫
    [operator]jenkins+gitlab/Webhook自动构建发布
    [GO]并发实现聊天室服务器
    [GO]文件的收发服务器
  • 原文地址:https://www.cnblogs.com/i-honey/p/7712243.html
Copyright © 2011-2022 走看看