覺得說得不錯,轉載一下。
鏈接:https://www.nowcoder.com/questionTerminal/98dc82c094e043ccb7e0570e5342dd1b
來源:牛客網
最長公共子串和最長公共子序列。。。傻傻煩不清楚
舉個栗子:
str1=”123ABCD456” str2 = “ABE12345D”
最長公共子序列是:12345
最長公共子串是:123
這兩個都可以用動態規劃,只是狀態轉移方程有點區別
最長公共子序列是:
dp[i][j] -- 表示子串str1[0...i]和子串str2[0...j]的最長公共子序列
當str1[i] == str2[j]時,dp[i][j] = dp[i-1][j-1] + 1;
否則,dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
最優解爲dp[len1-1][len2-1];
最長公共子串是: dp[i][j] -- 表示以str1[i]和str2[j]爲結尾的最長公共子串 當str1[i] == str2[j]時,dp[i][j] = dp[i-1][j-1] + 1; 否則,dp[i][j] = 0;
最優解爲max(dp[i][j]),其中0<=i<len1, 0<=j<len2;
so,代碼如下: //求最長公共子串
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String str1 = "";
String str2 = "";
while(sc.hasNext()){
str1 = sc.next();
str2 = sc.next();
System.out.println(getCommonStrLength(str1, str2));
}
}
public static int getCommonStrLength(String str1, String str2){
int len1 = str1.length();
int len2 = str2.length();
int[][] dp = new int[len1+1][len2+1];
for(int i=0;i<=len1;i++){
for(int j=0;j<=len2;j++){
dp[i][j] = 0;
}
}
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(str1.charAt(i-1) == str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = 0; //區別在這兒
}
}
}
int max = 0;
for(int i=0;i<=len1;i++){
for(int j=0;j<=len2;j++){
if(max < dp[i][j])
max = dp[i][j];
}
}
return max;
}
}
//求最長公共子序列 import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String str1 = "";
String str2 = "";
while(sc.hasNext()){
str1 = sc.next();
str2 = sc.next();
System.out.println(getCommonStrLength(str1, str2));
}
}
public static int getCommonStrLength(String str1, String str2){
int len1 = str1.length();
int len2 = str2.length();
int[][] dp = new int[len1+1][len2+1];
for(int i=0;i<=len1;i++){
for(int j=0;j<=len2;j++){
dp[i][j] = 0;
}
}
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(str1.charAt(i-1) == str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]); //區別在這兒
}
}
}
return dp[len1][len2];
}
}