最长公共字符串

对于最长公共字符串问题:
我的方法是采用动态规划求解,所有格子默认为0,当字符相同时就在对应的格子填入其左上角数字加1的结果。然后格子中的最大值即最大公共字符串的长度。
这里写图片描述

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
//str1为横向,str2这纵向
const string LCS(const string& str1, const string& str2){
    int x = str1.length();
    int y = str2.length();
    int data[100][100] = {0};

    int pos = -1;
    int max = 0;
    for(int i = 0; i < x; i ++)
    {
        for(int j = 0; j < y; j ++)
        {
            if(str2[j] == str1[i])
            {
                //左上角数字加1
                data[i+1][j+1] = data[i][j] + 1;
                if(data[i+1][j+1] > max)
                {
                    max = data[i+1][j+1];
                    pos = j;
                } 
            }   
        }
    }
    ///获取最长公共字符串
    string res = str2.substr(pos - max + 1 ,max);
    return res;
}
int main(){
    string str1("helloworldandc");
    string str2("world");
    string lcs = LCS(str1, str2);
    cout << lcs << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值