求两个输入序列的最长的公共子字符串的长度。子字符串中的所有字符在源字符串中必须相邻。
如字符串:21232523311324和字符串312123223445,他们的最长公共子字符串为21232,长度为5.
假设需要求的字符串为 str1 , str2 .函数 f(m,n) 求分别以str1[m] , str2[n] 结尾的公共字符串长度。
这有一下递推公式:
f(m,n)=0 str1[m] != str2[n]
f(m,n)=f(m-1,n-1) + 1 str[m]==str2[n]
别忘了递推的特殊边界:
f(0,n)=0
f(m,0)=0
/** * 两个字符串的最长公共子串 */ public class LongestCommonSubString { public int getSubString(String s, String t){ int[][] dp = new int[s.length()][t.length()]; //dp[i][j]:表示s[0:i]和t[0:j]的公共子串长度 int max = 0; for(int i = 0; i < s.length(); i++){ for(int j = 0; j < t.length(); j++){ if(s.charAt(i) == t.charAt(j)) { if (i == 0 || j == 0){ dp[i][j] = 1;//防止下面的数组溢界 }else { dp[i][j] = 1 + dp[i - 1][j - 1]; } } else { dp[i][j] = 0; } max = Math.max(dp[i][j], max); } } return max; } public static void main(String[] args) { LongestCommonSubString longestCommonSubString = new LongestCommonSubString(); int result = longestCommonSubString.getSubString("asdc", "sdcc"); System.out.println(result); } }
最长公共子序列https://blog.youkuaiyun.com/fkyyly/article/details/83068542