最长公共子序列与子串

来源:互联网 发布:三峡大坝的危害 知乎 编辑:程序博客网 时间:2024/04/28 04:32

子序列与子串的区别在于子序列不必是原字符串中的连续字符。

最长公共子串:

#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#define M 100
char* LCS(char left[],char right[])
{    //LCS问题就是求两个字符串最长公共子串的问题
    int lenLeft=strlen(left),lenRight=strlen(right),k;
    //获取左子串的长度,获取右子串的长度
    char*c=(char *)malloc(lenRight),*p;//注意这里要写成char型,而不是int型,否则输入整型数据时会产生错误。      //矩阵c纪录两串的匹配情况
    int start,end,len,i,j;//start表明最长公共子串的起始点,end表明最长公共子串的终止点
    end=len=0;//len表示最长公共子串的长度
    for(i=0;i<lenLeft;i++)//串1从前向后比较
    {    for(j=lenRight-1;j>=0;j--)//串2从后向前比较
        {    if(left[i] == right[j])//元素相等时
            {    if(i==0||j==0)
                    c[j]=1;
                else
                {    c[j]=c[j-1]+1;
                }
            }
            else
                c[j] = 0;
            if(c[j] > len)
            {    len=c[j];
                end=j;
            }
        }
    }
    start=end-len+1;
    p =(char*)malloc(len+1);//数组p纪录最长公共子串
    for(i=start; i<=end;i++)
    {    p[i-start] = right[i];
    }
    p[len]='/0';
    return p;
}
int main()
{    char str1[M],str2[M];
    printf("请输入字符串1:");
    gets(str1);
    printf("请输入字符串2:");
    gets(str2);
    printf("最长子串为:");
    printf("%s/n",LCS(str1,str2));
    system("PAUSE");
    return 0;
}

 

#include <iostream>
#include <string>
#define Max 100
using namespace std;
string X,Y;
int i,j,m,n,c[Max][Max],b[Max][Max];
int LCSlength(string X,string Y)
{
    m=X.length();
    n=Y.length();
    for(i=0;i<m;i++)
        c[i][0]=0;
    for(j=0;j<n;j++)
        c[0][j]=0;
    for(i=1;i<m;i++)
    {
        for(j=1;j<n;j++)
        {
            if(X[i]==Y[j])
            {
                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;
            }
        }
    }
    return c[m-1][n-1];
}
void PrintLCS(int i,int j)
{
    if(i==0||j==0)
        return;
    if(b[i][j]==1)
    {
        PrintLCS(i-1,j-1);
        cout<<X[i];   
    }
    else if(b[i][j]==2)
        PrintLCS(i-1,j);
    else
        PrintLCS(i,j-1);
}
void main()
{
    cout<<"请输入字符串X:/n";
    cin>>X;
    cout<<"请输入字符串Y:/n";
    cin>>Y;
    m=X.length();
    n=Y.length();
    X=" "+X;
    Y=" "+Y;
    cout<<"LCS-Length:"<<LCSlength(X,Y)<<endl;
    cout<<"LCS:";
    PrintLCS(m-1,n-1);
    cout<<"/n构造矩阵C为:/n";
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            cout<<c[i][j]<<" ";
            if(j==n-1)   
                cout<<endl;
        }
    }
    cout<<"构造矩阵B为:/n";
    for(i=0;i<m;i++)
    {
        for(j=0;j<n;j++)
        {
            cout<<b[i][j]<<" ";
            if(j==n-1)   
                cout<<endl;
        }
    }
}

原创粉丝点击