gpt4 book ai didi

python-3.x - 如何从两个字符串中生成最短的字符串

转载 作者:行者123 更新时间:2023-12-04 04:14:36 25 4
gpt4 key购买 nike

我想编写一个从两个字符串A,B返回最短字符串C的函数,并确保字符串A,B是C的子字符串。但是关键是A的长度不必比B长
前任:

A: 'abcd', B: 'cde' = > C: 'abcde' # c,d is duplicated
A: 'abcd', B: 'ecd' = > C: 'abcdecd' #no character duplicated so C is A + B
A: 'abc', B: 'cdeab' = > C: 'cdeabc'
A: 'bce', B: 'eabc' = > C: 'eabce' #length of eabcd is 5, length of bceabc is 6
A: '', B: 'abc' = > C: 'abc'
A: '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:]

最佳答案

您可以从头开始备份,寻找类似的比赛:

代码:

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

测试代码:
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'])

关于python-3.x - 如何从两个字符串中生成最短的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com