LintCode-最长公共子串

题目描述:

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

 注意事项

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

样例

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

 1 public class Solution {
 2     /**
 3      * @param A, B: Two string.
 4      * @return: the length of the longest common substring.
 5      */
 6     public int longestCommonSubstring(String A, String B) {
 7         // write your code here
 8         int maxLength = 0;
 9         if(A==null || B==null)
10             return 0;
11         for (int i = 0; i < A.length(); i++) {
12             for (int j = 0; j < B.length(); j++) {
13                 if (B.charAt(j) == A.charAt(i)) {
14                     int k = j + maxLength, l = i + maxLength;
15                     if (k >= B.length() || l >= A.length())
16                         break;
17                     else if(B.substring(j, j + maxLength).equals(A.substring(i, i + maxLength))) {
18 
19                         while (B.charAt(k) == A.charAt(l)) {
20                             maxLength++;
21                             k++;
22                             l++;
23                             if (k >= B.length() || l >= A.length())
24                                 break;
25 
26                         }
27                     }
28                 }
29             }
30         }
31         return maxLength;
32     }
33 }
原文地址:https://www.cnblogs.com/xiaocainiao2hao/p/5364484.html