求最长公共字串

 比如:"abcdkkk" 和 "baabcdadabc",两个字符串 求最长公共字串 也即“abcd” 输出返回字符串长度。

如图

 1 public class Main {
 2     public static void main(String[] args) {
 3         int n = f("abcddkkk", "baabcddadabc");
 4         System.out.println(n);
 5     }
 6 
 7     public static int f(String s1, String s2) {
 8         char[] c1 = s1.toCharArray();
 9         char[] c2 = s2.toCharArray();
10         int [][] arr = new int[c1.length+1][c2.length+1];
11         int max = 0;
12         for(int i=1;i<arr.length;i++){
13             for(int j=1;j<arr[i].length;j++){
14                 if(c1[i-1] == c2[j-1]){
15                     arr[i][j] = arr[i-1][j-1]+1;
16                     if(arr[i][j]>max){
17                         max = arr[i][j];
18                     }
19                 }
20             }
21         }
22         return max;
23     }
24 }
原文地址:https://www.cnblogs.com/csong7876/p/8630473.html