版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yexiguafu/article/details/51476191
设M=str1.length(),N=str2.length();
时间复杂度O(M*N),额外空间复杂度也是O(M*N).
建立一个M*N矩阵dp。 其中dp[i][j]表示在必须把str[i]和str2[j]当做公共子串最后一个字符的情况下,公共子串最长能多长。
JAVA代码:
<span style="font-size:18px;">import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
while (N-- > 0) {
String str1 = sc.next();
String str2=sc.next();
//StringBuffer sb = new StringBuffer(str1);
//String str2 = sb.reverse().toString();
int length1 = longSubString(str1, str2);
//System.out.println(str1.length() - length1);
System.out.println(length1);
}
}
public static int longSubString(String str1, String str2) {
int max = 0;
int m = str1.length();
int n = str2.length();
int dp[][] = new int[m][n];
for (int i = 0; i < m; i++)
if (str1.charAt(i) == str2.charAt(0)) {
dp[i][0] = 1;
max = 1;
}
for (int i = 0; i < n; i++)
if (str2.charAt(i) == str1.charAt(0)) {
dp[0][i] = 1;
max = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (str1.charAt(i) == str2.charAt(j)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
max = Math.max(max, dp[i][j]);
}
}
}
return max;
}</span>