最长公共子串c语言
❶ 求两个输入的字符串的最长公共子串
算法:求两个字符串的最长公共子串
原理:
(1) 将连个字符串分别以行列组成一个矩阵。
(2)。若该矩阵的节点对应的字符相同,则该节点值为1。
(3)当前字符相同节点的值 = 左上角(d[i-1, j-1])的值 +1,这样当前节点的值就是最大公用子串的长。
(s2)bcde
(s1)
a0000
b1000
c0200
d0030
3. 结果:只需以行号和最大值为条件即可截取最大子串
C# code:
[csharp]view plainprint?
publicstaticstringMyLCS(strings1,strings2)
{
if(String.IsNullOrEmpty(s1)||String.IsNullOrEmpty(s2))
{
returnnull;
}
elseif(s1==s2)
{
returns1;
}
intlength=0;
intend=0;
int[,]a=newint[s1.Length,s2.Length];
for(inti=0;i<s1.Length;i++)
{
for(intj=0;j<s2.Length;j++)
{
intn=(i-1>=0&&j-1>=0)?a[i-1,j-1]:0;
a[i,j]=s1[i]==s2[j]?1+n:0;
if(a[i,j]>length)
{
length=a[i,j];
end=i;
}
}
}
returns1.Substring(end-length+1,length);
}
❷ C璇瑷 链闀垮叕鍏卞瓙涓
棣栧厛鎸囧嚭妤间富镄勯敊璇
链闀跨殑鍏鍏卞瓙瀛楃︿覆 搴旇ユ敼鎴 链闀跨殑杩炵画鍏鍏卞瓙瀛楃︿覆
涓嬮溃鏄绗﹀悎妤间富瑕佹眰镄勫弬钥冧唬镰
//浣滆:hacker
//镞堕棿:9.12.2006
#include <stdio.h>
#include <string.h>
void main()
{
char* x="aabcdababce";
char* y="12abcabcdace";
int m = strlen(x);
int n = strlen(y);
int i, j, k, l;
int maxlength = 0;
int start = 0;
int count = 0;//鐢ㄦ潵鍒ゆ柇鏄钖﹀尮閰岖殑鍙橀噺
for (i=1;i<=n;i++)//鍖归厤闀垮害镄勫惊鐜
for (j=0;j<n-i+1;j++)//y镄勮捣濮嬩綅缃镄勫惊鐜
for (k=0;k<m-i+1;k++)//x镄勮捣濮嬩綅缃镄勫惊鐜
{
count = 0;
for (l=0;l<i;l++)//鍒ゆ柇鏄钖﹀尮閰,浠g爜鍙浠ヤ紭鍖
if (y[j+l] == x[k+l])
count++;
if (count==i&&i>maxlength)
{
maxlength = i;//璁板綍链澶ч暱搴
start = j;//璁板綍链澶ч暱搴︾殑璧疯捣浣岖疆
}
}
//浣滆:hacker
//镞堕棿:9.12.2006
#include <stdio.h>
#include <string.h>
void main()
{
char* x="aabcdababce";
char* y="12abcabcdace";
int m = strlen(x);
int n = strlen(y);
int i, j, k, l;
int maxlength = 0;
int start = 0;
int count = 0;//鐢ㄦ潵鍒ゆ柇鏄钖﹀尮閰岖殑鍙橀噺
for (i=1;i<=n;i++)//鍖归厤闀垮害镄勫惊鐜
for (j=0;j<n-i;j++)//y镄勮捣濮嬩綅缃镄勫惊鐜
for (k=0;k<m-i;k++)//x镄勮捣濮嬩綅缃镄勫惊鐜
{
count = 0;
for (l=0;l<i;l++)//鍒ゆ柇鏄钖﹀尮閰,浠g爜鍙浠ヤ紭鍖
if (y[j+l] == x[k+l])
count++;
if (count==i&&i>maxlength)
{
maxlength = i;//璁板綍链澶ч暱搴
start = j;//璁板綍链澶ч暱搴︾殑璧疯捣浣岖疆
}
}
if (maxlength==0)
printf("No Answer");
else
for (i=0;i<maxlength;i++)
printf("%c",y[start+i]);
}
}
涓嬮溃鏄鐪熸g殑链闀垮叕鍏卞瓙涓茬殑锷ㄦ佽勫垝绠楁硶
//浣滆:hacker
//镞堕棿:9.12.2006
#include <stdio.h>
#include <string.h>
int b[50][50];
int c[50][50];
void lcs(x,m,y,n)
char *x;
int m;
char *y;
int n;
{
int i;
int j;
for (i=1;i<=m;i++) c[i][0] = 0;
for (i=1;i<=n;i++) c[0][i] = 0;
c[0][0] = 0;
for (i=1;i<=m;i++)
for (j=1;j<=n;j++)
{
if (x[i-1] == y[j-1])
{
c[i][j] = c[i-1][j-1] + 1;
b[i][j] = 1;
}
else
if (c[i-1][j] > c[i][j-1])
{
c[i][j] = c[i-1][j];
b[i][j] = 2;
}
else
{
c[i][j] = c[i][j-1];
b[i][j] = 3;
}
}
}
void show(i,j,x)
int i;
int j;
char* x;
{
if (i==0||j==0)
return;
if (b[i][j]==1)
{
show(i-1,j-1,x);
printf("%c",x[i-1]);
}
else
if (b[i][j]==2)
show(i-1,j,x);
else
show(i,j-1,x);
}
void main()
{
char* x="aabcdababce";
char* y="12abcabcdace";
int m = strlen(x);
int n = strlen(y);
lcs(x,m,y,n);
show(m,n,x);
}