[ Algorithm ] LCS 算法 动态规划解决

LCS算法简述:

求出一个未知序列 s0 ,如果是两个或多个已知序列s1、s2、s3......sn的子序列,

则 未知序列s0 称为已知S序列集的最长公共子序列。

而最长公共子串(要求连续)和最长公共子序列是不同的。

算法原理,不一一细讲。

code 0 :

public static int Get_LCS_Length(string query, string keyword)
{
    if (query == keyword) return query.Length;

    int MaxLength = 0;
    int QueryLength = query.Length;
    int KeyWordLength = keyword.Length;

    int[] QueryMatrix = new int[QueryLength >= KeyWordLength ? QueryLength : KeyWordLength];

    if ((String.IsNullOrEmpty(query)) || (String.IsNullOrEmpty(keyword))) return 0;
    if (query.IndexOf(keyword) > -1) return KeyWordLength;

    for (int i = 0; i < QueryLength; i++)
    {
        for (int j = 0; j < KeyWordLength; j++)
        {
            if (query[i] == keyword[j])
            {
                if ((i == 0) || (j == 0)) QueryMatrix[j] = 1;
                else QueryMatrix[j] = QueryMatrix[j - 1] + 1;
            }

            if (QueryMatrix[j] > MaxLength) MaxLength = QueryMatrix[j];
        }
    }
    return MaxLength;
}

 

 

 

posted @ 2013-07-05 16:22  程序员文道  阅读(720)  评论(0编辑  收藏  举报