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

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

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

#include <iostream>
#include <vector>
using namespace std;

int main() {
    string str1, str2;
    while (cin >> str1 >> str2) {
        int result = 0; 
        if (str1.length() > str2.length()) //使较小的字符串在前
            swap(str1, str2);
        int m = str1.size(), n = str2.size();
        vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
        int index = 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;
                }
                if (dp[i][j] > result) {
                    result = dp[i][j];
                    index = i - 1;
                }

            }
        }
        cout << str1.substr(index - result + 1, result) << endl;
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

07-14 13:37
重庆大学 C++
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
S_Holmes:一想到我苦苦追求的迪子私下里却是985的马子,我的心就在滴血😭😭😭
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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