1.题目描述
给定两个只包含小写字母的字符串,计算两个字符串的最大公共子串的长度。
注:子串的定义指一个字符串删掉其部分前缀和后缀(也可以不删)后形成的字符串。
例如:
输入:
asdfas
werasdfaswer
输出:
6
2.思路分析
这里要注意,这是最大公共子串,而不是公共子序列。这就要求,符合要求的元素之间都是连续的。
我们用动态规划的思想来做题。
针对一个状态F(i, j),i是第一个字符串的第i个元素,j是第二个字符串中的第j个元素。
举一个例子:
F(1, 1) = 0,因为第一个字符串的第1个元素是a,第二个字符串的第1个元素是w,二者不相等。
如果F(i,j)满足第一个字符串中的第i个元素和第二个字符串中的第j个元素相等的话,那么必定有一个或多个公共子串。F(1, 4) = 1. F(2, 5) = F(1, 4) + 1.
即每个状态都要使用上一个状态的结果。
状态转移方程:
F(i,j) = F(i - 1, j - 1) + 1;
3.代码
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String str1 = sc.nextLine();
String str2 = sc.nextLine();
char[] ch1 = str1.toCharArray();
char[] ch2 = str2.toCharArray();
System.out.println(med(ch1, ch2));
}
}
public static int med(char[] ch1, char[] ch2){
int[][] arr = new int[ch1.length + 1][ch2.length + 1];
int maxCount = 0;
for(int i = 1; i < ch1.length + 1; i++){
for(int j = 1; j < ch2.length + 1; j++){
if(ch1[i-1] == ch2[j-1]){
arr[i][j] = arr[i-1][j-1] + 1;
}
if(maxCount < arr[i][j]){
maxCount = arr[i][j];
}
}
}
return maxCount;
}
}