最长公共子串(LCS)

找两个字符串的最长公共子串,这个子串要求在原字符串中是连续的。其实这又是一个序贯决策问题,可以用动态规划来求解。我们采用一个二维矩阵来记录中间的结果。这个二维矩阵怎么构造呢?直接举个例子吧:"bab"和"caba"(当然我们现在一眼就可以看出来最长公共子串是"ba"或"ab")

   b  a  b

c  0  0  0

a  0  1  0

b  1  0  1

a  0  1  0

我们看矩阵的斜对角线最长的那个就能找出最长公共子串

不过在二维矩阵上找最长的由1组成的斜对角线也是件麻烦费时的事,下面改进:当要在矩阵是填1时让它等于其左上角元素加1。

   b  a  b

c  0  0  0

a  0  1  0

b  1  0  2

a  0  2  0

这样矩阵中的最大元素就是 最长公共子串的长度。

在构造这个二维矩阵的过程中由于得出矩阵的某一行后其上一行就没用了,所以实际上在程序中可以用一维数组来代替这个矩阵。(滚动数组设计,就是这个一维数组可以重复使用)

代码如下:


#include<iostream>
#include<cstring>
#include<vector>
#include<string.h>
using namespace std;
//str1为横向,str2这纵向

const string LCS(const string& str1,const string& str2){
    int xlen=str1.size();         //横向长度

    vector<int> tmp(xlen);        //保存矩阵的上一行
    vector<int> arr(tmp);         //当前行

    int ylen=str2.size();         //纵向长度
    int maxele=0;                 //矩阵元素中的最大值
    int pos=0;                    //矩阵元素最大值出现在第几列

    //int arr1[10];
    //memset(arr1,0,sizeof(arr1));
    
    for(int i=0;i<ylen;i++){      //纵向长度,相当于为y轴
        string s=str2.substr(i,1);//就是单一的字符

        arr.assign(xlen,0);       //数组清0


        for(int j=0;j<xlen;j++){  //横向长度,以横向作为位置的记录,相当于为x轴
            if(str1.compare(j,1,s) == 0){// xlen=str1.size(); 
                if(j==0)
                    arr[j]=1;
                else
                    arr[j]=tmp[j-1]+1;

                if(arr[j]>maxele){
                    maxele=arr[j];
                    pos=j;
                }
            }
        }
//      {
//          vector<int>::iterator iter=arr.begin();
//          while(iter!=arr.end())
//              cout<<*iter++;
//          cout<<endl;
//      }
        tmp.assign(arr.begin(),arr.end());//字符串的赋值
    }
    string res=str1.substr(pos-maxele+1 , maxele);//输出的为行的位置,位置和长度
    return res;
}

int main(){
    string str1("21232523311324"); //21232,横向长度
    string str2("312123223445");   
    string lcs=LCS(str1,str2);
    cout<<lcs<<endl;
    return 0;
}

https://www.cnblogs.com/zhangchaoyang/articles/2012070.html

猜你喜欢

转载自blog.csdn.net/while_black/article/details/89609112