Longest Common Substring

来源:互联网 发布:大便出血 鲜红色 知乎 编辑:程序博客网 时间:2024/06/05 18:25

Given two strings, find the longest common substring.
Return the length of it.

Note
The characters in substring should occur continiously in original string. This is different with subsequnce.
Example
Given A=“ABCD”, B=“CBCE”, return 2


很著名的LCS问题。我们需要得到最大长度的公共子串的长度。如果暴力破解的话,首先得枚举出A所有的子串和B所有的子串,再根据比较得到最大长度的公共子串的长度,复杂度太高。
因此想到DP解法。
这里dp[i][j]可不是表示A的前i个字符与B的前j个字符的LCS。因为substring是连续的,对于这种连续的问题DP实际是记录当前元素“取或不取”。
所以dp[i][j]的含义是含有A中第i个字符和B中第j个字符的LCS。
dp[i][j] = dp[i - 1][j - 1] + 1 if A[i] == B[j]
dp[i][j] = 0 if A[i] != B[j]

public class Solution {    /**     * @param A, B: Two string.     * @return: the length of the longest common substring.     */    public int longestCommonSubstring(String A, String B) {        // write your code here        int[][] dp = new int[A.length() + 1][B.length() + 1];        for(int i = 1; i < dp.length; i++){            for(int j = 1; j < dp[0].length; j++){                if(A.charAt(i - 1) == B.charAt(j - 1)){                    dp[i][j] = dp[i - 1][j - 1] + 1;                }else{                    dp[i][j] = 0;                }            }        }        int max = 0;        for(int i = 0; i < dp.length; i++){            for(int j = 0; j < dp[0].length; j++){                max = Math.max(max, dp[i][j]);            }        }        return max;    }}
0 0
原创粉丝点击