gpt4 book ai didi

java - WAP 返回两个字符串之间最长公共(public)子串的长度

转载 作者:行者123 更新时间:2023-12-01 10:54:44 26 4
gpt4 key购买 nike

给定两个字符串,我们必须找到最长公共(public)子串的长度。我不知道我的代码有什么问题。

外层循环获取 B 的子字符串,内层循环每次将子字符串增加一个字符。

对于输入“www.lintcode.com code”、“www.ninechapter.com code”,输出是 5,但应该是 9

    public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here
int k = 0, temp = 0;
if(B.length() == 0){
return 0;
}

for(int i = 0; i < B.length()-1; i++){
String bb = B.substring(i, i+1);
if(A.contains(bb)){

for(int j = 1; j < A.length()-i; j++){
String bbb = B.substring(i, i+j);
if(!A.contains(bbb))
break;
temp = bbb.length();
}
}
if(temp > k)
k = temp;
}

return k;
}

}

最佳答案

只需替换这个:

for(int j = 1; j < A.length()-i; j++)

这样:

for(int j = 1; j < B.length()-i+1; j++)

关于java - WAP 返回两个字符串之间最长公共(public)子串的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676992/

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