fork download
  1. import java.util.Scanner;
  2.  
  3. public class Main
  4. {
  5. public static void main(String[] args) {
  6. Scanner scanner = new Scanner(System.in);
  7.  
  8. // 提示用户输入两个字符串
  9. System.out.print("请输入第一个字符串: ");
  10. String str1 = scanner.nextLine();
  11.  
  12. System.out.print("请输入第二个字符串: ");
  13. String str2 = scanner.nextLine();
  14.  
  15. // 调用findLongestCommonSubstring方法找到最长公共子串
  16. String longestCommonSubstring = findLongestCommonSubstring(str1, str2);
  17.  
  18. // 输出最长公共子串
  19. System.out.println("最长公共子串为: " + longestCommonSubstring);
  20.  
  21. scanner.close();
  22. }
  23.  
  24. // 找到两个字符串的最长公共子串
  25. public static String findLongestCommonSubstring(String str1, String str2) {
  26. int[][] dp = new int[str1.length() + 1][str2.length() + 1];
  27. int maxLength = 0;
  28. int endIndex = 0;
  29.  
  30. for (int i = 1; i <= str1.length(); i++) {
  31. for (int j = 1; j <= str2.length(); j++) {
  32. if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
  33. dp[i][j] = dp[i - 1][j - 1] + 1;
  34. if (dp[i][j] > maxLength) {
  35. maxLength = dp[i][j];
  36. endIndex = i;
  37. }
  38. } else {
  39. dp[i][j] = 0;
  40. }
  41. }
  42. }
  43.  
  44. return str1.substring(endIndex - maxLength, endIndex);
  45. }
  46. }
  47.  
Success #stdin #stdout 0.18s 60840KB
stdin
qwert
weryuiuhnji
stdout
请输入第一个字符串: 请输入第二个字符串: 最长公共子串为: wer