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

Example 1:
    Input:  "ABCD" and "CBCE"
    Output:  2
    Explanation:
    Longest common substring is "BC"
Example 2:
    Input: "ABCD" and "EACB"
    Output:  1
    Explanation: 
    Longest common substring is 'A' or 'C' or 'B'
dp[i][j]代表String A中以第i个字符为结尾与String B中第j个字符为结尾的lcs‘的长度
(此lcs’结尾必须为A的第i个字符和B的第j个字符,所以只有A的第i个字符和B的第j个字符相同情况下dp[i][j]才会在原基础上+1,要不就等于0)
public class Solution {
    public int longestCommonSubstring(String A, String B) {
        int[][] dp = new int[A.length() + 1][B.length() + 1];
        int max = 0;
        for(int i = 1; i < A.length() + 1; i++) {
            for(int j = 1; j < B.length() + 1; j++) {
                if(A.charAt(i-1) == B.charAt(j-1)) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                    max = Math.max(max, dp[i][j]);
                } else dp[i][j] = 0;
            }
        }
        return max;
    }
}

results matching ""

    No results matching ""