题解 | #公共子串计算#

公共子串计算

https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b

dp[i][j]表示str1以i为结尾和str2以j结尾的最大公共子串的长度
if(str1[i-1]==str2[j-1]) dp[i][j] = dp[i-1][j-1]+1;
else dp[i][j] = 0;//注意我们要求的是连续的以i,j为结尾的。
dp[0][0] = 0;

#include <iostream>
#include <bits/stdc++.h>
#include <vector>
using namespace std;

int main() {
    string str1,str2;
    while(cin>>str1>>str2){
        int m = str1.size(),n = str2.size();
        /*dp[i][j]表示str1以i为结尾和str2以j结尾的最大公共子串的长度
        if(str1[i-1]==str2[j-1]) dp[i][j] = dp[i-1][j-1]+1;
        else dp[i][j] = 0;
        dp[0][0] = 0;
        */
        int result = 0;
        vector<vector<int>>dp(m+1,vector<int>(n+1,0));
        for(int i = 1;i<=m;i++){
            for(int j = 1;j<=n;j++){
                if(str1[i-1]==str2[j-1]) dp[i][j] = dp[i-1][j-1]+1;
                else dp[i][j] = 0;
                result = result>dp[i][j]?result:dp[i][j];
            }
        }
        cout<<result<<endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务