题解 | 公共子串计算
公共子串计算
https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b
#include <iostream> #include <ostream> #include <string> using namespace std; int main() { string a,b; cin >> a >>b; if(a.size()<b.size()){ swap(a,b); } for(int i = b.size(); i >= 0; i--){ for(int j = 0 ; j < b.size() - i + 1; j++){ string now = b.substr(j,i); if(a.find(now) != a.npos){ cout << i << endl; return 0; } } } return 0; } // 64 位输出请用 printf("%lld")
这个题目,细节就细节在截取字符串这里,这两的两个for循环,第二个for循环条件设置为 b.size() - i + 1;substr只是设置了一个开始,这个条件就能保证在截取长度一定的前提下能够开始的位置根本就不多。