问题描述
假如有两个字符串,s1="people"和s2="eplm",我们要求他俩最长的公共子串。
示例:
输入:
s1="people" s2="eplm"
输出:
2,因为s1和s2公共最长子串是pl
解:
1、暴力求解:暴力求解对于字符串比较短的我们还可以接受,如果字符串太长实在是效率太低,所以这种我们就不再考虑
2、动态规划:我们用一个二维数组dp[i][j]表示第一个字符串前i个字符和第二个字符串前j个字符组成的最长公共字符串的长度,那么我们在计算dp[i][j]的时候,我们首先要判断s1.charAt(i)是否等于s2.charAt(j),如果不相等,说明当前字符无法构成公共子串,所以dp[i][j]=0。如果相等,说明可以构成公共子串,我们还要加上他们前一个字符构成的最长公共子串长度,也就是dp[i-1][j-1]。所以我们很容易找到递推公式:
递推公式:
if(s1.charAt(i) == s2.charAr(j)) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = 0;
最长公共子串画图分析:
我们看到在动态规划中,最大值不一定是在最后一个空格内,所以我们要使用一个临时变量在遍历的时候记录下最大值。代码如下:
public static int maxLong(String str1, String str2) { if (str1 == null || str2 == null || str1.length() == 0 || str2.length() == 0) return 0; int max = 0; int[][] dp = new int[str1.length() + 1][str2.length() + 1]; for (int i = 1; i <= str1.length(); i++) { for (int j = 1; j <= str2.length(); j++) { if (str1.charAt(i - 1) == str2.charAt(j - 1)) { dp[i][j] = dp[i][j] + 1; } else { dp[i][j] = 0; } max = Math.max(max, dp[i][j]); } } return max; }