题解 | #查找两个字符串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")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务