LintCode-最长公共子串

题目描述:

  给出两个字符串,找到最长公共子串,并返回其长度。

注意事项

  子串的字符应该连续的出现在原字符串中,这与子序列有所不同。

样例

  给出A=“ABCD”,B=“CBCE”,返回 2

 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 maxLength = 0;
if(A==null || B==null)
return 0;
for (int i = 0; i < A.length(); i++) {
for (int j = 0; j < B.length(); j++) {
if (B.charAt(j) == A.charAt(i)) {
int k = j + maxLength, l = i + maxLength;
if (k >= B.length() || l >= A.length())
break;
else if(B.substring(j, j + maxLength).equals(A.substring(i, i + maxLength))) { while (B.charAt(k) == A.charAt(l)) {
maxLength++;
k++;
l++;
if (k >= B.length() || l >= A.length())
break; }
}
}
}
}
return maxLength;
}
}
上一篇:Asp.Net MVC学习总结之过滤器详解(转载)


下一篇:Python发送微信消息