现在的位置: 首页 > 综合 > 正文

求两个字符串的最长公共子串

2019年01月04日 ⁄ 综合 ⁄ 共 1291字 ⁄ 字号 评论关闭

from:http://blog.csdn.net/mjx20045912/article/details/6928934

今天看到关于求两个字符串的最长公共子串的算法,写出来和大家分享一下。

算法:求两个字符串的最长公共子串

原理:

1。 将连个字符串分别以行列组成一个矩阵。

2。若该矩阵的节点对应的字符相同,则该节点值为1。

3。当前字符相同节点的值 = 左上角(d[i-1, j-1])的值 +1,这样当前节点的值就是最大公用子串的长。

       (s2)  b  c    d  e

(s1)

a             0  0    0   0

b             1   0   0   0

c             0    2   0  0

d             0    0   3  0

 

结果:只需以行号和最大值为条件即可截取最大子串

 

C# code:

 

[csharp] view
plain
copy

  1. public static string MyLCS(string s1, string s2)  
  2.        {  
  3.            if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2))  
  4.            {  
  5.                return null;  
  6.            }  
  7.            else if (s1 == s2)  
  8.            {  
  9.                return s1;  
  10.            }  
  11.            int length = 0;  
  12.            int end = 0;  
  13.            int[,] a = new int[s1.Length, s2.Length];  
  14.            for (int i = 0; i < s1.Length; i++)  
  15.            {  
  16.                for (int j = 0; j < s2.Length; j++)  
  17.                {  
  18.                    int n = (i - 1 >= 0 && j - 1 >= 0) ? a[i - 1, j - 1] : 0;  
  19.                    a[i, j] = s1[i] == s2[j] ? 1+n : 0;  
  20.                    if (a[i, j] > length)  
  21.                    {  
  22.                        length = a[i,j];  
  23.                        end = i;  
  24.                    }  
  25.                }  
  26.            }  
  27.            return s1.Substring(end - length + 1, length);  
  28.        }  

抱歉!评论已关闭.