最长公共子串问题

序:本人算法太弱,每逢面试,总会在算法题上卡下壳。昨晚面度面试,虽然总体感觉不错,但是唯一的一道算法题依然没有回答上。这道题是求最长公共子串,其实很多同学都讨论过这个问题了,我偏是没有重视。亡羊补牢,在此作下笔记,希望能吸取些教训。

摘自: http://www.yuanma.org/data/2006/0723/article_1215.htm

题目描述:

求字符串str1, str2的最长公共子串的长度。

算法思想:   

定义二元函数f(m,n)为分别以str1[m],str2[n]结尾的连续公共子串的长度(注:如果公共子串非空并且以str1[m]和str2[n]结尾,则必有str1[m] = str2[n])

而对于f(m+1,n+1) 有以下两种情况

1.str1[m+1] != str2[n+1],则有f(m+1,n+1) =0

2.str1[m+1] == str2[n+1],则有f(m+1,n+1) = f(m,n) + 1

另外f(0,j) = 0(j>=0)

       f(j,0) = 0 (j>=0)

按照上面这个公式,我们用容易写出这个算法的实现

1int commstr(char*str1, char*str2)
2/* 返回str1,str2的最长公共之串长度*/
3 {
4int len1=strlen(str1),len2=strlen(str2),row,col,max=0;
5int**pf =newint*[len1+1];//动态分配一个二维数组作为辅助空间
6for (row=0; row<len1+1; row++)
7 pf[row] =newint[len2+1];
8
9//数组赋初值
10for (row=0; row<len1+1; row++)
11 pf[row][0] =0;
12for (col=0; col<len2+1; col++)
13 pf[0][col] =0;
14
15for (row=1; row<=len1; row++)
16for (col=1;col<=len2; col++)
17 {
18if (str1[row-1] == str2[col-1])
19 {
20 pf[row][col] = pf[row-1][col-1] +1;
21 max = pf[row][col] > max ? pf[row][col] : max;
22 }
23else
24 pf[row][col] =0;
25 }
26//空间回收
27for (row=0; row<len1+1; row++)
28 delete[] pf[row];
29 delete[] pf;
30
31return max;
32 }

posted on 2011-05-25 09:45  Joshua Leung  阅读(298)  评论(0编辑  收藏  举报

导航