Longest Common Subsequence Problem

The longest common subsequence (LCSproblem is the problem of finding the longest subsequence common to all sequences in a set of sequences (often just two sequences). It differs from problems of finding common substrings: unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences.

https://en.wikipedia.org/wiki/Longest_common_subsequence_problem

 

LCS function defined[edit]

Let two sequences be defined as follows: X = (x1x2...xm) and Y = (y1y2...yn). The prefixes of X are X1, 2,...m; the prefixes of Y are Y1, 2,...n. Let LCS(XiYj) represent the set of longest common subsequence of prefixes Xi and Yj. This set of sequences is given by the following.

LCS\left(X_{i},Y_{j}\right) = \begin{cases}   \empty & \mbox{ if }\ i = 0 \mbox{ or }  j = 0 \\   \textrm{  } LCS\left(X_{i-1},Y_{j-1}\right) \frown x_{i} & \mbox{ if } x_i = y_j \\   \mbox{longest}\left(LCS\left(X_{i},Y_{j-1}\right),LCS\left(X_{i-1},Y_{j}\right)\right) & \mbox{ if } x_i \ne y_j \\ \end{cases}

To find the longest subsequences common to Xi and Yj, compare the elements xi and yj. If they are equal, then the sequence LCS(Xi-1Yj-1) is extended by that element, xi. If they are not equal, then the longer of the two sequences, LCS(XiYj-1), andLCS(Xi-1Yj), is retained. (If they are both the same length, but not identical, then both are retained.) Notice that the subscripts are reduced by 1 in these formulas. That can result in a subscript of 0. Since the sequence elements are defined to start at 1, it was necessary to add the requirement that the LCS is empty when a subscript is zero.

 

Computing the length of the LCS

The function below takes as input sequences X[1..m] and Y[1..n] computes the LCS between X[1..i] and Y[1..j] for all 1 ≤ i ≤ m and 1 ≤ j ≤ n, and stores it in C[i,j]C[m,n] will contain the length of the LCS of X and Y.

function LCSLength(X[1..m], Y[1..n])
    C = array(0..m, 0..n)
    for i := 0..m
       C[i,0] = 0
    for j := 0..n
       C[0,j] = 0
    for i := 1..m
        for j := 1..n
            if X[i] = Y[j]
                C[i,j] := C[i-1,j-1] + 1
            else
                C[i,j] := max(C[i,j-1], C[i-1,j])
    return C[m,n]

Example Question:
http://www.lintcode.com/en/problem/longest-common-subsequence/
http://www.lintcode.com/en/problem/longest-common-substring/

转载于:https://www.cnblogs.com/midan/p/4688049.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值