【问题标题】:How to find longest intersection between two strings in python?如何在python中找到两个字符串之间的最长交集?
【发布时间】:2020-08-07 01:19:04
【问题描述】:

我正在尝试编写一个程序来找到两个字符串之间最长的交集。条件是:

  1. 如果没有公共字符,程序将返回一个空链。
  2. 如果有多个长度相同的公共字符的子字符串,它应该返回最大的那个,例如,对于“bbaacc”和“aabb”,重复的子字符串是“aa”和“bb”,但作为“bb” > "aa",所以程序必须只返回 "bb"。
  3. 最后,程序应该返回最长的公共子字符串,例如,对于“programme”和“grammaire”,返回应该是“gramm”而不是“gramme”。

我的代码在最后一个条件下存在问题,我该如何更改它以使其按预期工作?

def intersection(v, w):
    if not v or not w:
        return ""
    x, xs, y, ys = v[0], v[1:], w[0], w[1:]
    if x == y:
        return x + intersection(xs, ys)
    else:
        return max(intersection(v, ys), intersection(xs, w), key=len)

司机:

print(intersection('programme', 'grammaire'))

【问题讨论】:

  • 这是最长公共子序列问题的变体。它可以使用动态规划来解决。

标签: python string intersection


【解决方案1】:

找不到你的代码的问题,但我是这样解决的

def longest_str_intersection(a: str, b: str):

    # identify all possible character sequences from str a
    seqs = []
    for pos1 in range(len(a)):
        for pos2 in range(len(a)):
            seqs.append(a[pos1:pos2+1])
        
    # remove empty sequences
    seqs = [seq for seq in seqs if seq != '']

    # find segments in str b
    max_len_match = 0
    max_match_sequence = ''
    for seq in seqs:
        if seq in b:
            if len(seq) > max_len_match:
                max_len_match = len(seq)
                max_match_sequence = seq

    return max_match_sequence


longest_str_intersection('programme', 'grammaire')
-> 'gramm'

也有兴趣看看你是否找到了更优雅的解决方案!

【讨论】:

    猜你喜欢
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多