如何从两个字符串生成最短的字符串

sln*_*sln 9 python-3.x

我想编写一个函数来从两个字符串A,B中返回最短的字符串C,并确保字符串A,B是C的子字符串.但是键的长度A不必长于B ex:

A:'abcd',B:'cde'=> C:'abcde'#c,d是重复的
A:'abcd',B:'ecd'=> C:'abcdecd'#no字符重复,所以C是A + B
A:'abc',B:'cdeab'=> C:'cdeabc'A:'bce'
,B:'eabc'=> C:'eabce'#eabcd的长度为5,bceabc的长度为6
答:'',B:'abc'=> C:'abc'
答:'abc',B:''=> C:'abc'

我有以下功能,但似乎不正确

def checksubstring(A, B):
    if not A or not B: return A if not B else B
    index, string = 0, ''
    for i, c in enumerate(A):
        index = index + 1 if c == B[index] else 0
        string += c
    return string + B[index:]
Run Code Online (Sandbox Code Playgroud)

Ste*_*uch 6

您可以从最后查找匹配,如:

码:

def shortest_substring(a, b):

    def checksubstring(a, b):
        if not a or not b:
            return b or a

        for i in range(1, len(b)):
            if a[len(a) - i:] == b[:i]:
                return a + b[i:]
        return a + b

    x = checksubstring(a, b)
    y = checksubstring(b, a)
    return x if len(x) <= len(y) else y
Run Code Online (Sandbox Code Playgroud)

测试代码:

results = [
    {'A': 'abcd', 'B': 'cde', 'C': 'abcde'},
    {'A': 'abcd', 'B': 'ecd', 'C': 'abcdecd'},
    {'A': 'abc', 'B': 'cdeab', 'C': 'cdeabc'},
    {'A': 'bce', 'B': 'eabc', 'C': 'eabce'},
    {'A': '', 'B': 'abc', 'C': 'abc'},
    {'A': 'abc', 'B': '', 'C': 'abc'},
]

for result in results:
    assert result['C'] == shortest_substring(result['A'], result['B'])
Run Code Online (Sandbox Code Playgroud)