最長公共子序列與子串

子序列與子串的區別在於子序列不必是原字符串中的連續字符。

最長公共子串:

#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;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章