字符串——最长公共子串(长度、子串)

 1     public static int longestCommonSubstring(String s1, String s2) {
 2         int len1 = s1.length();
 3         int len2 = s2.length();
 4         int result = 0;
 5         int[] index = new int[2];
 6         for(int i=0; i<len1; i++) {
 7             for(int j=0; j<len2; j++) {
 8                 int m = i;
 9                 int n = j;
10                 while(m<len1 && n<len2) {
11                     if(s1.charAt(m) == s2.charAt(n)) {
12                         m++;
13                         n++;
14                     }else {
15                         break;
16                     }
17                 }
18                 if((n-j) > result) {
19                     result = n-j;
20                     index[0] = j;
21                     index[1] = n;22                 }
23             }
24         }
25         System.out.println(s2.substring(index[0], index[1]));
26         return result;
27     }

 

posted @ 2019-05-03 21:23  往南的小燕子  阅读(653)  评论(0编辑  收藏  举报