gpt4 book ai didi

java - 从两个字符串中找到相似子串的方法

转载 作者:搜寻专家 更新时间:2023-11-01 03:29:49 24 4
gpt4 key购买 nike

我正在使用这段 Java 代码来查找相似的字符串:

if( str1.indexof(str2) >= 0 || str2.indexof(str1) >= 0 ) ......

但是对于 str1 = "pizzabase"str2 = "namedpizzaowl" 它不起作用。

如何找到常见的子字符串,例如“pizza”?

最佳答案

遍历 str1 中的每个字母,检查它是否存在于 str2 中。如果它不存在,则继续下一个字母,如果存在,则将您在 str2 中检查的 str1 中的子字符串的长度增加到两个字符,并重复直到找不到更多匹配项或您已遍历 str1

这会发现所有共享的子串,但是 - 就像冒泡排序 - 几乎不是最优的,而是一个如何解决问题的非常基本的例子。

类似于这个伪示例:

pos = 0
len = 1
matches = [];

while (pos < str1.length()) {

while (str2.indexOf(str1.substring(pos, len))) {
len++;
}

matches.push(str1.substring(pos, len - 1));
pos++;
len = 1;
}

关于java - 从两个字符串中找到相似子串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3509163/

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