题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <iostream> using namespace std; int main() { string a; string b; getline(cin, a); getline(cin, b); string tem; string res; if (a.size() > b.size()) { for (int i = 0, j = 0; j < b.size();) { tem = b.substr(i, len); if (a.find(tem) == a.npos) { i++; j = i + len; } else { res = tem; j++; len++; } } } else { for (int i = 0, j = 0; j < a.size();) { tem = a.substr(i, len); if (b.find(tem) == b.npos) { i++; j = i + len; } else { res = tem; j++; len++; } } } cout << res; }
从短的字符串中获取子字符串,然后去长的字符串中找该短的字符串,找到的话让子字符串长度+1再去找,没找到就长度不变,子字符开头向后移一位去找。