import java.util.Scanner; public class Main { public static Scanner sc = new Scanner(System.in); public static void main(String[] args) { String s1 = sc.nextLine(); String s2 = sc.nextLine(); // String s1 = "1AB2345CD"; // String s2 = "12345EF"; int n1 = s1.length(); int n2 = s2.length(); char[] arr1 = s1.toCharArray(); char[] arr2 = s2.toCharArray(); int maxLen = 0; int maxI = 0; // 斜着的一一计算 int si = 0; int sj = n1 -1; while (true){ if(si == n2-1 && sj == 0){ break; } int len = 0; int i = si; int j = sj; if(arr2[i] == arr1[j]){ len = 1; } if(len > maxLen){ maxLen = len; maxI = i; } while (i < n2 && j < n1){ i++; j++; if(i >= n2 || j >= n1){ break; } if(arr2[i] == arr1[j]){ len = len + 1; }else { len = 0; } // System.out.println(i + " " + j + " " + len); if(len > maxLen){ maxLen = len; maxI = i; } } if(sj > 0){ sj --; }else{ si ++; } } if(maxLen == 0){ System.out.println(-1); return; } String ans = ""; while (maxLen-- > 0){ ans = arr2[maxI] + ans; maxI--; } System.out.println(ans); } } /* 1AB2345CD 12345EF 2345 */
dp[i][j]
只依赖dp[i-1][j-1]
, 可以斜着来
import java.util.Scanner; public class Main { public static Scanner sc = new Scanner(System.in); public static void main(String[] args) { String s1 = sc.nextLine(); String s2 = sc.nextLine(); // String s1 = "1A2C3D4B56"; // String s2 = "B1D23CA45B6A"; int n1 = s1.length(); int n2 = s2.length(); char[] arr1 = s1.toCharArray(); char[] arr2 = s2.toCharArray(); int maxLen = 0; int maxI = 0; int[][] dp = new int[n2][n1]; for(int i=0;i<n2;i++){ if(arr1[0] == arr2[i]){ dp[i][0] = 1; maxLen = 1; maxI = i; } } for(int i=0;i<n1;i++){ if(arr2[0] == arr1[i]){ dp[0][i] = 1; maxLen = 1; maxI = 0; } } for(int i=1;i<n2;i++){ for(int j=1;j<n1;j++){ if(arr2[i] == arr1[j]){ dp[i][j] = dp[i-1][j-1] + 1; } if(dp[i][j] > maxLen){ maxLen = dp[i][j]; maxI = i; } } } // for(int i=0;i<n2;i++){ // for(int j=0;j<n1;j++){ // System.out.print(dp[i][j] + " "); // } // System.out.println(); // } if(maxLen == 0){ System.out.println(-1); return; } String ans = ""; while (maxLen-- > 0){ ans = arr2[maxI] + ans; maxI--; } System.out.println(ans); } } /* 1AB2345CD 12345EF 2345 */