一、题目内容

image.png

二、题解

解法1:

思路

image.png

代码

  1. public class Solution {
  2. /**
  3. * longest common substring
  4. * @param str1 string字符串 the string
  5. * @param str2 string字符串 the string
  6. * @return string字符串
  7. */
  8. public String LCS(String str1, String str2) {
  9. // write code here
  10. if (str1 == null || str2 == null) {
  11. return null;
  12. }
  13. int m = str1.length();
  14. int n = str2.length();
  15. int[][] dp = new int[m][n];
  16. int maxLength = 0;
  17. int lastIndex = 0;
  18. for (int i = 0; i < m; i++) {
  19. for (int j = 0; j < n; j++) {
  20. if (str1.charAt(i) == str2.charAt(j)) {
  21. if (i == 0 || j == 0) {
  22. dp[i][j] = 1;
  23. } else {
  24. dp[i][j] = dp[i - 1][j - 1] + 1;
  25. }
  26. if (dp[i][j] > maxLength) {
  27. maxLength = dp[i][j];
  28. lastIndex = i;
  29. }
  30. }
  31. }
  32. }
  33. return str1.substring(lastIndex - maxLength + 1, lastIndex + 1);
  34. }
  35. }