Longest Common Substring


Given two strings, find the longest common substring.

Return the length of it.

Example

Given A = "ABCD", B = "CBCE", return 2.

public class Solution {
    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
    public int longestCommonSubstring(String A, String B) {
        int maxlen = 0;
        int m = A.length();
        int n = B.length();
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < m; j++) {
                int len = 0;
                while (i + len < m && j + len < n && A.charAt(i + len) == B.charAt(j + len)) {
                    len++;
                    maxlen = Math.max(maxlen, len);
                }
            }
        }
        return maxlen;
    }
}
原文地址:https://www.cnblogs.com/iwangzheng/p/5802112.html