码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Longest Common Substring

时间:2015-11-11 06:29:29      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

Longest Common Substring

Given two strings, find the longest common substring.

Return the length of it.

Example

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

Note

The characters in substring should occur continuously in original string. This is different with subsequence.

Challenge

O(n x m) time and memory.

 

SOLUTION:

DP经典题。

状态: 如果是这种比较经典的最大最小,总数,问题,直接结合问题去做状态。f(i, j) = A以(i)结尾,B以(j)结尾时,LCS

方程: 1,i,j位置字母相同 直接+1。 2不相同的话直接为零。

初始化:初始化为0.

答案,f(i,j)中的最大值。

 

技术分享
public class Solution {
    /**
     * @param A, B: Two string.
     * @return: the length of the longest common substring.
     */
    public int longestCommonSubstring(String A, String B) {
        int[][] result = new int[A.length() + 1][B.length() + 1];
        if (A == null || B == null){
            return 0;
        }
        int max = 0;
        for (int i = 1; i <= A.length(); i++){
            for (int j = 1; j <= B.length(); j++){
                if (A.charAt(i - 1) == B.charAt(j - 1)){
                    result[i][j] = result[i - 1][j - 1] + 1;
                } else {
                    result[i][j] = 0;
                }
                max = Math.max(max, result[i][j]);
            }
        }
        return max;
    }
}
View Code

 

[LintCode] Longest Common Substring

标签:

原文地址:http://www.cnblogs.com/tritritri/p/4955109.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!