1.最长公共子序列和最长公共连续子序列(子串)
以"hellowrold","loop"为例
1.1非连续(子序列)
这个状态转移方程要好好领悟
dp[i+1][j+1] = Math.max(dp[i][j+1],dp[i+1][j]);
2.连续(子串)
package leetcodego.dp;
import java.util.Scanner;
public class LCS {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
int x = sc.nextInt();
//连续子序列
if(x==1){
for(int i=0;i<s1.length();i++){
for(int j=0,k=s1.length()-i;j<s2.length()&&k<s2.length();j++,k++){
String str = s1.substring(j,k+1);
if(s2.contains(str)){
System.out.println(str.length());
return;
}
}
}
}
//非连续子序列dp
if(x==2){
//dp[i+1][j+1]截止到s1的第i个,s2的第j个,最长公共子序列
int[][] dp = new int[s1.length()+1][s2.length()+1];
for(int i=0;i<s1.length();i++){
for(int j=0;j<s2.length();j++){
if(s1.charAt(i)==s2.charAt(j))
dp[i+1][j+1]=dp[i][j]+1;
else dp[i+1][j+1] = Math.max(dp[i][j+1],dp[i+1][j]);
}
}
System.out.println(dp[s1.length()][s2.length()]);
}
//连续子序列dp
if(x==3){
//dp[i+1][j+1]:以s1的第i个,s2的第j个结尾的最长公共子序列
int[][] dp = new int[s1.length()+1][s2.length()+1];
int max=0;
for(int i=0;i<s1.length();i++){
for(int j=0;j<s2.length();j++){
if(s1.charAt(i)==s2.charAt(j)){
dp[i+1][j+1]=dp[i][j]+1;
max = Math.max(max,dp[i+1][j+1]);
}
else dp[i+1][j+1] = 0;
}
}
System.out.println(max);
}
}
}