题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

#include <algorithm>
#include <any>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
    string str1, str2;
    cin >> str1 >> str2;
    if(str1.length() > str2.length()) swap(str1, str2);//规定str1为较短串
    vector<vector<int>> dp(str1.length()+1, vector<int>(str2.length()+1, 0));
    int subStrLen = 0;//记录当前求得最长公共子串的长度
    int left = 0;//记录当前求得最长公共子串在str1中的起始位置
    for(int i = 1; i <= str1.length(); i++){
        for(int j = 1; j <= str2.length(); j++){
            if(str1[i-1] == str2[j-1]){
                dp[i][j] = dp[i-1][j-1] + 1;
                if(dp[i][j] > subStrLen){
                    subStrLen = dp[i][j];
                    left = i - subStrLen;
                }
            }
        }
    }
    cout << str1.substr(left, subStrLen) << endl;
    return 0;
}

全部评论

相关推荐

粉红恶魔派星星:炸了,偶遇kpi面。面试官一直在忙自己的事情。1.手写责任链 2.手写快排 3.linux定时任务的命令 4.springboot的定时任务 5.问了一条实习
今天你投了哪些公司?
点赞 评论 收藏
分享
求问!考研下岸,打算参加春招,我这个bg能进啥厂,或者需要搞点深度项目再投吗
Java抽象带篮子_...:直接海投,可以看看我的考研失利速成冲春招贴,里面详细写了简历怎么写,学哪些项目可以速成
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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