题解 | #最长公共子串#
最长公共子串
https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac
import java.util.*; public class Solution { public String LCS (String str1, String str2) { int m = str1.length(), n = str2.length(); String[][] dp = new String[m + 1][n + 1]; String max = ""; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { if(i == 0 || j == 0){ dp[i][j] = ""; }else if (str1.charAt(i-1) == str2.charAt(j-1)) { dp[i][j] = dp[i-1][j-1] + str1.charAt(i-1); if (max.length() < dp[i][j].length()) { max = dp[i][j]; } }else{ dp[i][j] = ""; //与最长公共子序列不同 这里不连续的话直接为空, } } } return max.length() == 0 ? "-1" : max; } }代码思路与最长公共子序列一致,只有一行代码不同,这样比较好记忆