OJ_1042 Coincidence

本文介绍了一种使用动态规划解决两个字符串最长公共子串问题的方法。通过构建二维DP数组来记录不同位置上的子串匹配长度,从而找到最长公共子串的长度。适用于字符串长度不超过100的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <string>
using namespace std;
int getmax(int a,int b)
{
    return a>b?a:b;
}
void func()
{
     string s1;
     string s2;
     while(cin>>s1>>s2)
     {
                     int **dp=new int*[101];
                     for(int i=0;i<=s1.size();i++)
                     {
                             dp[i]=new int[101];
                             for(int j=0;j<=s2.size();j++)
                                     dp[i][j]=0;
                     }    
                                         
                     for(int i=1;i<=s1.size();i++)
                     {
                             for(int j=1;j<=s2.size();j++)
                             {
                                     if(s1[i-1]==s2[j-1])
                                     {
                                           dp[i][j]=dp[i-1][j-1]+1;          
                                     }else{
                                           dp[i][j]=getmax(dp[i-1][j],dp[i][j-1]);
                                     }
                                     
                             }
                     }
                     cout<<dp[s1.size()][s2.size()]<<endl;
                       
     }
    
   
}
int main(int argc, char *argv[])
{
    
	//printf("Hello, world\n");
	func();
	return 0;
}


DP,最大公共子串

题目描述:

Find a longest common subsequence of two strings.

输入:

First and second line of each input case contain two strings of lowercase character a…z. There are no spaces before, inside or after the strings. Lengths of strings do not exceed 100.

输出:

For each case, output k – the length of a longest common subsequence in one line.

样例输入:
abcd
cxbydz
样例输出:
2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值