动态规划
package com.String; public class zichuan { public static void main(String[] args) { String s1="1AB2345CD"; String s2="12345EE"; System.out.println(LCS(s1,s2)); } public static String LCS(String s1,String s2){ int maxLenth=0;//最长公共子串的长度 int maxLastIndex=0;//最长公共子串最后一个元素在s1中的位置 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; if (dp[i+1][j+1]>maxLenth){ maxLenth=dp[i+1][j+1]; maxLastIndex=i; } } else {//字符不相等 dp[i+1][j+1]=0; } } } return s1.substring(maxLastIndex-maxLenth+1,maxLastIndex+1); } }