[英]WAP to return the length of longest common substring between two strings
Two strings are given and we have to find the length of longest common substring. 给出了两个字符串,我们必须找到最长的公共子字符串的长度。 I don't know what's wrong with my code.
我不知道我的代码有什么问题。
The outer loop takes a substring of B and the inner loop increases the substring by one character at a time. 外循环使用B的子字符串,而内循环一次将子字符串增加一个字符。
For the input "www.lintcode.com code", "www.ninechapter.com code" the output is coming 5 but it should be 9 对于输入“ www.lintcode.com代码”,“ www.ninechapter.com代码”,输出为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;
}
} }
Just replace this: 只需替换为:
for(int j = 1; j < A.length()-i; j++)
with this: 有了这个:
for(int j = 1; j < B.length()-i+1; j++)
I believe you could reduce your function size a little with this...not sure if your method is more efficient or not though... 我相信您可以使用此方法来稍微减小函数的大小...虽然不确定您的方法是否更有效...
public int longestCommonSubstring(String A, String B) {
int longestSubstring = 0;
for (int x=0; x < A.length(); x++) {
for (int y=x; y < A.length() + 1; y++) {
String testString = A.substring(x,y);
if (B.contains(testString) && (testString.length() > longestSubstring)) {
longestSubstring = testString.length();
}
}
}
return longestSubstring;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.