题解 | 公共子串计算

#include <iostream>
using namespace std;

int main() {
    string s, t;
    cin >> s >> t;

    int len_s = s.size();
    int len_t = t.size();

    string temp = "";
    int temp_len = 0;
    int max_len = 0;
    if (len_s <= len_t) {
        if (len_s == 1) {
            if (t.find(s) != t.npos) {
                max_len = 1;
            } else {
                max_len = 0;
            }
        } else {
            for (int i = 0; i < s.size() - 1; i ++) {
                for (int j = i + 1; j < s.size(); j ++) {
                    temp = s.substr(i, j - i + 1);
                    temp_len = j - i + 1;
                    if (t.find(temp) != t.npos) {
                        if (temp_len > max_len) {
                            max_len = temp_len;
                        }
                    } else {
                        continue;
                    }
                }
            }
        }

    } else {
        if (len_t == 1) {
            if (s.find(t) != s.npos) {
                max_len = 1;
            } else {
                max_len = 0;
            }
        } else {
            for (int i = 0; i < t.size() - 1; i ++) {
                for (int j = i + 1; j < t.size(); j ++) {
                    temp = t.substr(i, j - i + 1);
                    temp_len = j - i + 1;
                    if (s.find(temp) != s.npos) {
                        if (temp_len > max_len) {
                            max_len = temp_len;
                        }
                    } else {
                        continue;
                    }
                }
            }
        }
    }

    cout << max_len << endl;

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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