最长公共字串和最长公共子序列

来源:互联网 发布:淘宝拍卖的包是真的吗 编辑:程序博客网 时间:2024/05/16 01:17

LintCode 最长公共字串

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

建立一个矩阵来保存两个字符串出现相同字符的地方,比如“abccd”和“abcefc”就有

abccd

a10000

b02000

c00300

e00040

f00000

c00100

这样就有每次遇到相等的都加上下他的斜上方的位置的值,然后使用一个max变量来记录目前的最大值即可

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        char[] as = A.toCharArray();        char[] bs = B.toCharArray();        int[][] f = new int[bs.length][as.length];        int max = 0;        for(int i = 0; i < bs.length; i++){            for(int j =0; j < as.length; j++){                int pre = (i-1 >= 0 && j-1 >= 0)?f[i-1][j-1]:0;                if(bs[i] == as[j]){                    f[i][j] = 1+pre;                    max = Math.max(f[i][j],max);                }            }        }        return max;    }}


LintCode 最长公共子序列

给出两个字符串,找到最长公共子序列(LCS),返回LCS的长度。

这个题和最长公共字串的区别就在于公共字串必须是连着的,但是这个可以不连着!

对于公共子序列其实也是要建立一个m*n的矩阵A来记录当前的最长子序列的长度,但是矩阵更新的规则变成:


public class Solution {    /**     * @param A, B: Two strings.     * @return: The length of longest common subsequence of A and B.     */    public int longestCommonSubsequence(String A, String B) {        // write your code here        char[] as = A.toCharArray();        char[] bs = B.toCharArray();        int[][] f = new int[bs.length][as.length];        int max = 0;        for(int i = 0; i < bs.length; i++){            for(int j = 0; j < as.length; j++){                int pre = (i-1 >= 0 && j-1 >= 0)?f[i-1][j-1]:0;                if(bs[i] == as[j]){                    f[i][j] = 1 + pre;                }                else                f[i][j] = Math.max(i-1>=0? f[i-1][j]:0,j-1>=0?f[i][j-1]:0);                  max = Math.max(f[i][j], max);            }        }        return max;    }}



0 0
原创粉丝点击