不同于公共子串 不需要连续
package com.String; public class zixu { public static void main(String[] args) { String s1="1A2C3D4B56"; String s2="B1D23A456A"; System.out.println(LCS(s1,s2)); } public static String LCS(String s1,String s2){ int len1=s1.length(); int len2=s2.length(); if (len1==0||len2==0) return "-1"; int[][] dp=new int[len1+1][len2+1]; for (int i = 0; i < len1+1; i++) { for (int j = 0; j < len2+1; j++) { if (i==0||j==0){ dp[i][j]=0;//初始化行列第一个元素 continue; } if (s1.charAt(i-1)==s2.charAt(j-1)){//charAt(0)检索字符串中的第一个字符 dp[i][j]=dp[i-1][j-1]+1; } else { dp[i][j]=Math.max(dp[i-1][j],dp[i][j-1]); } } } //返回 找出一个最长的公共子序列 StringBuilder ss=new StringBuilder(); while (len1!=0&&len2!=0){ if (s1.charAt(len1-1)==s2.charAt(len2-1)){ ss.append(s1.charAt(len1-1)); len1--; len2--; } else { if (dp[len1-1][len2]>dp[len1][len2-1]){ len1--; } else { len2--; } } } if (ss.length()==0) return "-1"; return ss.reverse().toString(); } }