提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目描述
给定两个只包含小写字母的字符串,计算两个字符串的最大公共子串的长度。
注:子串的定义指一个字符串删掉其部分前缀和后缀(也可以不删)后形成的字符串。
输入描述:
输入两个只包含小写字母的字符串
输出描述:
输出一个整数,代表最大公共子串的长度
示例1
输入
asdfas
werasdfaswer
输出
6
题目来源:牛客网
解题过程
解题思路
动态规划:动态规划的二维数组装的是对应子串的最大公共子串长度。dp[i][j]保存的就是子串m:0-i和子串n:0-j 的最大公共子串长度。
import java.util.*;
public class Main{
public static void main(String [] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNextLine()){
String m_str = scanner.nextLine();
String n_str = scanner.nextLine();
int [][] dp = new int[m_str.length()+1][n_str.length()+1];
int max = 0;
for(int i = 1; i <= m_str.length(); i++){
for(int j = 1; j <= n_str.length(); j++){
if(m_str.charAt(i-1) == n_str.charAt(j-1)){
dp[i][j] = dp[i - 1][j - 1] + 1;
max = Math.max(dp[i][j], max);
}
}
}
System.out.println(max);
}
}
}
总结
暂时没有总结,待续。。。