本质是最长公共子序列
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
int n1 = s1.length();
int n2 = s2.length();
int n = 0;
int m = 0;
int[] flags1 = new int[n1+1];
int cnt = 0;
for(int i = 0;i<n1;i++){
if(Character.isUpperCase(s1.charAt(i))){
n++;
flags1[cnt++] = i;
}
}
flags1[cnt] = n1;
cnt = 0;
int[] flags2 = new int[n2+1];
for(int i = 0;i<n2;i++){
if(Character.isUpperCase(s2.charAt(i))){
m++;
flags2[cnt++] = i;
}
}
flags2[cnt] = n2;
int[][] dp = new int[n+1][m+1];
int ans = 0;
for(int i = 1;i<=n;i++){
for(int j = 1;j<=m;j++){
if(s1.substring(flags1[i-1],flags1[i]).equals(s2.substring(flags2[j-1],flags2[j]))){
dp[i][j] = Math.max(dp[i][j],dp[i-1][j-1]+1);
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}
System.out.println(dp[n][m]);
}
}
最长公共子序列模板
int[][] dp = new int[n+1][n+1];
for(int i = 1;i<=n;i++){
for(int j = 1;j<=n;j++){
if(s.charAt(i-1) == rs.charAt(j-1)){
dp[i][j] = Math.max(dp[i][j],dp[i-1][j-1] + 1);
}else{
dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
}