数据结构实验之最长公共子序列

实验目的

1、了解串的基本概念

2、掌握求最长公共子序列的算法

  • 实验内容和代码

设计并实现,求最长公共子序列的算法。使用动态规划算法解决最长公共子序列问题:给定两个序列X={x1,x2,…,xm}和Y={y1,y2,…,yn},找出X和Y的最长公共子序列。(使用动态规划的思想)(递归)

#include<iostream>

#include<stack>

#include<string>

#include<cstring>

using namespace std;

void GetLCS(string &str1, string &str2){

    int m = str1.length() + 1;

    int n = str2.length() + 1;

    int length[m][n];

    int state[m][n];

    memset( state, 100, sizeof(state) );//初始化函数,将全部内容设定为指定的值

    for(int i=0; i<m; i++){  //初始化第1列

        length[i][0] = 0;

    }

    for(int j=0; j<n; j++){//初始化第1行

        length[0][j] = 0;

    }

    for(int i=1; i<m; i++){

        for(int j=1; j<n; j++){

            if(str1[i-1] == str2[j-1]) {

                length[i][j] = length[i-1][j-1] + 1;

                state[i][j] = 0;

            }else if(length[i][j-1] >= length[i-1][j]) {

                length[i][j] = length[i][j-1];

                state[i][j] = -1;  //列数减一

            }else {

                length[i][j] = length[i-1][j];

                state[i][j] = 1;  //行数减一

            }

        }

    }

    //打印最长子序列

    stack<char> lcs;//常用栈函数,栈的一些基本操作包括在stack文件中

    for(int i=m-1, j=n-1; i>=0 && j>=0;){

        if(state[i][j] == 0){//说明str1的第i个元素和str2的第j个元素相同       

            lcs.push(str1[i-1]);

            i--;

            j--;

        }else if(state[i][j] == 1){

            i--;  //行数减一

        }else{

            j--; //列数减一

        }

    }

    if(lcs.empty()){

        cout<<"没有公共子序列"<<endl;

        return ;

    }

    cout<<"最长的子序列:";

    while(!lcs.empty()){

        cout<<lcs.top();

        lcs.pop();

    }

    cout<<"\n其长度为:"<<length[m-1][n-1];

    return ;

}

int main(){

    string str1 = "abcdefghijklmnree";

    string str2 = "cdfgrrze";

    cout<<"序列1:"<<str1<<endl;

    cout<<"序列2:"<<str2<<endl;

    GetLCS(str1,str2);

    return 0;

}

  • 实验小结

memset()函数是初始化函数,作用是将某一块内存中的全部内容设置为指定的值

序列1和序列2最大公共子序列有三种:BCAB、BDAB、BCBA,只能输出BDAB的情形

四、教师评语

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LucianaiB

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值