查找两个字符串之间的公共子字符串

编程入门 行业动态 更新时间:2024-10-24 10:21:32
本文介绍了查找两个字符串之间的公共子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想比较2个字符串并保持匹配,在比较失败的地方分开。

I'd like to compare 2 strings and keep the matched, splitting off where the comparison fails.

所以,如果我有2个字符串-

So if I have 2 strings -

string1 = apples string2 = appleses answer = apples

另一个例子,因为字符串可能有多个单词。

Another example, as the string could have more than one word.

string1 = apple pie available string2 = apple pies answer = apple pie

我敢肯定有一种简单的Python方式可以做到这一点,但我无法解决,

I'm sure there is a simple Python way of doing this but I can't work it out, any help and explanation appreciated.

推荐答案

它称为最长公共子字符串问题。在这里,我提出了一个简单,易于理解但效率低下的解决方案。为大型字符串生成正确的输出将花费很长时间,因为该算法的复杂度为O(N ^ 2)。

Its called Longest Common Substring problem. Here I present a simple, easy to understand but inefficient solution. It will take a long time to produce correct output for large strings, as the complexity of this algorithm is O(N^2).

def longestSubstringFinder(string1, string2): answer = "" len1, len2 = len(string1), len(string2) for i in range(len1): match = "" for j in range(len2): if (i + j < len1 and string1[i + j] == string2[j]): match += string2[j] else: if (len(match) > len(answer)): answer = match match = "" return answer print longestSubstringFinder("apple pie available", "apple pies") print longestSubstringFinder("apples", "appleses") print longestSubstringFinder("bapples", "cappleses")

输出

apple pie apples apples

更多推荐

查找两个字符串之间的公共子字符串

本文发布于:2023-11-02 17:43:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1553011.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!