题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 String stra = in.nextLine(); String strb = in.nextLine(); int a = stra.length(); int b = strb.length(); int maxLenth = 0; int endIndex =0; String result=""; String orderA=""; String orderB=""; if(a>b){ orderA = strb; orderB = stra; }else{ orderA = stra; orderB = strb; } int[][] dp = new int[orderA.length()+1][orderB.length()+1]; for(int i=1;i<=orderA.length();i++ ){ for(int k=1;k<=orderB.length();k++){ if(orderA.charAt(i-1)==orderB.charAt(k-1)) { dp[i][k] = dp[i-1][k-1]+1;//相同数目加1 if(dp[i][k]>maxLenth){ maxLenth = dp[i][k];//确定最长的长度 endIndex = i-1;//最后匹配终止的位置 } } } } outloop: for(int i=1;i<=orderA.length();i++){ for(int k=0;k<=orderB.length();k++){ if(dp[i][k]==maxLenth){ endIndex=i-1; break outloop; } } } result = orderA.substring(endIndex-maxLenth+1,endIndex+1); if(maxLenth == 0) System.out.println(""); else System.out.println(result); } }