【经典算法】:最长公共子序列(LCS问题,用遍历实现)

来源:互联网 发布:互动百科排名优化 编辑:程序博客网 时间:2024/06/05 19:42

题目

给出两个字符串,求两个字符串的最长公共子序列

思路

对两个字符串任意一个字符串s1进行遍历,然后查找s2中与s1[i]相同的位置,每次相同时就同时设两个变量pos1,pos2记录下位置然后往后比较,一直比较到不相同的时候为止,记录下来这个串的长度max。

每次得到max之后和之前的公共子串长度相比较,如果大于之前的,就把这次的子串长度设为是最长的

按照上述思路逐步进行,最后得到一个最长的子串以及其初始位置,输出即可

代码

//最长公共子序列问题// 测试数据 : aaccbkdabdaacc  aaccbbgcdaacc#include <iostream>using namespace std;int pos = 0,max =0;              //pos记录下标,max记录最大长度int main(){    char s0[1000],s1[1000];  //s0代表序列0 s1代表序列1    cin>>s0>>s1;    int len0 = strlen(s0),len1 = strlen(s1);    for(int i=0;i<len1;i++){        //这个指s1        for(int j =0;j<len0;j++){            if(s0[j]==s1[i]){                int temp_pos=i,temp_max=0,temp_i=i,temp_j=j;;                while(s1[temp_i]==s0[temp_j] &&temp_i<len1 &&temp_j<len0){                    temp_i++;                    temp_j++;                    temp_max++;                }                if(temp_max>max){                    pos = temp_pos;                     max = temp_max;                }            }        }    }    cout<<pos<<" "<<max<<endl;    for(int k=pos;k<pos+max;k++){        cout<<s1[k];    }    cout<<endl;}

运行截图

这里写图片描述

第一个参数0代表地址 ,第二个5代表子串长度

0 0