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

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

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

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

int main() {
    string s1, s2;
    while (cin >> s1 >> s2) {
        if (s1.length() > s2.length()) //使较小的字符串在前
            swap(s1, s2);
        string output = "";
        for (int i = 0; i < s1.length(); i++) { //遍历s1每个起始点
            for (int j = 0; j < s2.length(); j++) { //遍历s2每个起点
                int length = 0;
                int x = i, y = j;
                while (x < s1.length() && y < s2.length() &&
                        s1[x] == s2[y]) { //比较每个起点为始的子串
                    x++;
                    y++;
                    length++;
                }
                if (output.length() < length) //更新更大的长度子串
                    output = s1.substr(i, x - i);
            }
        }
        cout << output << endl;
    }
    return 0;
}

全部评论

相关推荐

05-01 22:41
中南大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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