[英]WAP to return the length of longest common substring between two strings
給出了兩個字符串,我們必須找到最長的公共子字符串的長度。 我不知道我的代碼有什么問題。
外循環使用B的子字符串,而內循環一次將子字符串增加一個字符。
對於輸入“ 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;
}
}
只需替換為:
for(int j = 1; j < A.length()-i; j++)
有了這個:
for(int j = 1; j < B.length()-i+1; j++)
我相信您可以使用此方法來稍微減小函數的大小...雖然不確定您的方法是否更有效...
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.