作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想编写一个从两个字符串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/
我是一名优秀的程序员,十分优秀!