擅长:python、mysql、java
<p>您可以在<code>while</code>循环中增加一个偏移量,以使公共字符与相应索引的偏移量保持串联,直到它们变得不同。要查找最长、不重叠的公共子字符串,可以使用递归遍历子字符串分区的不同路径的函数,并返回子字符串长度最长的路径:</p>
<pre><code>def common_strings(a, b, i=0, j=0):
candidates = []
len_a = len(a)
len_b = len(b)
if j == len_b:
candidates.append(common_strings(a, b, i + 1, 0))
elif i < len_a:
offset = 0
while i + offset < len_a and j + offset < len_b and a[i + offset].lower() == b[j + offset].lower():
offset += 1
if offset > 1:
candidates.append([a[i: i + offset]] + common_strings(a, b, i + offset, j + offset))
candidates.append(common_strings(a, b, i, j + 1))
return candidates and max(candidates, key=lambda t: sorted(map(len, t), reverse=True))
</code></pre>
<p>以便:</p>
<pre><code>print(common_strings('ABCDXGHIJ', 'ghijYAbCd'))
print(common_strings('Bonywasawarrior', 'Bonywasxwarrior'))
print(common_strings('01101001', '101010'))
</code></pre>
<p>输出:</p>
<pre><code>['ABCD', 'GHIJ']
['Bonywas', 'warrior']
['1010']
</code></pre>