[编程题] 最长公共子串

对于两个字符串,请设计一个时间复杂度为O(m*n)的算法(这里的m和n为两串的长度),求出两串的最长公共子串的长度。这里的最长公共子串的定义为两个序列U1,U2,..Un和V1,V2,...Vn,其中Ui + 1 == Ui+1,Vi + 1 == Vi+1,同时Ui == Vi。

给定两个字符串AB,同时给定两串的长度nm

测试样例:
"1AB2345CD",9,"12345EF",7
返回:4
解法思路:构造dp矩阵,不相等直接设置0,相等则由左上角+1,跟新dp,然后利用全局变量max寻找矩阵中的最大值。
 1 public int findLongest(String A, int n, String B, int m) {
 2         int[][] dp = new int[n+1][m+1];
 3         int max = 0;
 4         for (int i = 1; i <= n; i++) {
 5             for (int j = 1; j <= m; j++) {
 6                 if(A.charAt(i-1)==B.charAt(j-1)){
 7                     dp[i][j] = dp[i-1][j-1]+1;
 8                 }else{
 9                     dp[i][j] = 0;
10                 }
11                 max = Math.max(max,dp[i][j]);
12             }
13          }
14         return max;
15     }
Jumping from failure to failure with undiminished enthusiasm is the big secret to success.
原文地址:https://www.cnblogs.com/chongerlishan/p/6297813.html