最长公共子串

来源:互联网 发布:修改苹果手机型号软件 编辑:程序博客网 时间:2024/05/22 00:26

给出两个字符串,找到最长公共子串,并返回其长度。

样例

给出A=“ABCD”,B=“CBCE”,返回 2

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 t=0;        int l1 = A.length();        int l2 = B.length();        int[][] sum = new int[l1+1][l2+1];                for(int i=1; i<=l1; i++) {            char c1 = A.charAt(i-1);            for(int j=1; j<=l2; j++) {                char c2 = B.charAt(j-1);                if(c1==c2)                {                    sum[i][j] = sum[i-1][j-1]+1;                }                else{                    sum[i][j] = 0;                }                t = Math.max(t, sum[i][j]);            }        }        return t;    }}

这道题虽然是中等题,但事实上很简单,我的做法是把两个字符串的每个char从头对比,有点意思的是我用了二维数组来存储每次对比之后相同的个数。初始化的时候数组中每个数都为0,数组的定义比两个string的长度大1,然后从1开始循环。

0 0
原创粉丝点击