【问题标题】:How to get the index of the longest common substring?如何获取最长公共子串的索引?
【发布时间】:2019-10-14 09:58:26
【问题描述】:

任务是在最初的两个字符串中找到最长公共 substing 的索引,例如对于两个字符串'money''working for food not maney' 第一个字符串为 2,第二个字符串为 20。

获取最长子字符串的当前代码如下。如何修改下面的函数来获取初始字符串中最长子字符串的索引:

def get_len_long_substr(str1, str2):
    substring = ''
    len_str1 = len(str1)
    if len_str1 > 0:
        for i in range(len_str1):
            for j in range(len_str1 - i + 1):
                if j > len(substring) and all(str1[i:i + j] in x for x in [str1, str2]):
                    substring = str1[i:i + j]

    return len(substring), substring
get_len_long_substr('money', 'working for food not maney')
3, 'ney'
# Target index is 2, 20

【问题讨论】:

    标签: python arrays python-3.x string


    【解决方案1】:

    您确定第二个索引应该是 20 吗?我觉得应该是23...

    如果我是对的,请修改您的代码,如下所示

    def get_len_long_substr(str1, str2):
        substring = ''
        len_str1 = len(str1)
    
        if len_str1 > 0:
            for i in range(len_str1):
                for j in range(len_str1 - i + 1):
                    if j > len(substring) and all(str1[i:i + j] in x for x in [str1, str2]):
                        substring = str1[i:i + j]
    
            idx1 = str1.index(substring)
            idx2 = str2.index(substring)
    
        return idx1, idx2, len(substring), substring
    

    【讨论】:

    • 你说得对,大约 23 岁。str.index 的方法非常好 - 谢谢)
    猜你喜欢
    • 1970-01-01
    • 2014-04-14
    • 2016-06-03
    • 2010-11-28
    • 2015-06-23
    • 2020-07-31
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多