zoukankan      html  css  js  c++  java
  • Find Longest common string

    动态规划法:

    用二维矩阵来的每个元素来代表两个字符串的字符匹配情况,

    LCS[i, j]= LCS[i-1, j-1] + 1  , if X[i-1] == Y[J-1].

    LCS[i, j] =0, everything else

    每一个元素记载着两个字符串的相似程度,而且每个元素只需关心上一个元素的值来计算字符串比较的累计情况。

    实现代码:


           public static string LongestCommonString(string x, string y)
            {
                if (x == null || y == null)
                {
                    return null;
                }
    
                if (string.IsNullOrEmpty(x) || string.IsNullOrEmpty(y))
                {
                    return string.Empty;
                }
    
                int m = x.Length;
                int n = y.Length;
    
                int[,] LCS = new int[m, n];
                int result = 0;
                int mIndex = 0;
                int nIndex = 0;
    
                for(int i = 0; i < m; i++)
                {
                    for (int j = 0; j < n; j++)
                    {
                        if (i == 0 || j == 0)
                        {
                            LCS[i, j] = 0;
                        }
                        else if (x[i - 1] == y[j - 1])
                        {
                            LCS[i, j] = 1 + LCS[i - 1, j - 1];
                            if (result < LCS[i, j])
                            {
                                result = LCS[i, j];
                                mIndex = i;
                                nIndex = j;
                            }                        
                        }
                    }
                }
    
                StringBuilder sb = new StringBuilder();
                Stack<char> stack = new Stack<char>();
                while(result > 0)
                {
                    stack.Push(x[mIndex-1]);
                    result = LCS[mIndex-1, nIndex-1];
                    mIndex--;
                    nIndex--;
                }
    
                while(stack.Count > 0)
                {
                    sb.Append(stack.Pop());
                }
    
                return sb.ToString();
            }
  • 相关阅读:
    委托经典--由浅入深讲解
    原生的AJAX
    asp.net传值
    flex做的圣杯布局
    弹性盒布局实例
    CSS3实现的几个小loading效果
    requireJS基本概念及使用流程(2)
    require.js的基本概念及使用流程(1)
    JSz中的静态方法和实例方法的分析
    前端性能优化的方法
  • 原文地址:https://www.cnblogs.com/xuyanran/p/8594180.html
Copyright © 2011-2022 走看看