提取在第一个字符串的结尾和第二个字符串的开头常见的子字符串

Extract a substring that is common in ending of first string and beginning of second string

给定 2 个字符串

例如: "Hello World""World Is Awesome"

不完全是联合。我需要提取一个在第一个字符串结尾和第二个字符串开头常见的子字符串。

在上面的示例中,它将是 "World",因为第一个字符串以此字符列表结尾,第二个字符串以此字符列表开头。

最有效的方法是什么?可以是任何语言,但我主要对 python 和 c# 感到好奇。

这是我的解决方案

def union_chars(head, tail):
    match = None
    for i in range(len(head)):
        if tail.startswith(head[-i:]):
            match = head[-i:]
    return match

以下是使用 for 循环和索引的方法:

def union_chars(head, tail):
    for i in range(len(head)):
        if tail.startswith(head[i:]):
            return head[i:]

print(union_chars("Hello World", "World Is Awesome"))

输出:

World

解释:

首先,遍历head字符串的每个索引, 并检查 tail 字符串是否以 head 字符串的索引开头到 head string.Template

的结尾

这是一个基于 Ann Zen 答案的简化解决方案。我认为它效率更高一些,因为它不需要 len() 多次。并且更短

def union_chars(head, tail):
    match = None
    for i in range(len(head)):
        if tail.startswith(head[-i:]):
            match = head[-i:]
    return match