题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include<iostream> #include<string> #include<vector> using namespace std; string GetComSubstr(string &str1,string &str2) { if(str1.size()>str2.size()) swap(str1,str2); int len1=str1.size(); int len2=str2.size(); vector<vector<int>> MSC(len1+1,vector<int>(len2+1,0)); int start=0,Maxsize=0; for(int i=1;i<=len1;++i) { for(int j=1;j<=len2;++j) { if(str1[i-1]==str2[j-1]) MSC[i][j]=MSC[i-1][j-1]+1; if(MSC[i][j]>Maxsize) { Maxsize=MSC[i][j]; start=i-Maxsize; } } } return str1.substr(start,Maxsize); } int main() { string str1,str2; while(cin>>str1>>str2) { string substr=GetComSubstr(str1,str2); cout<<substr<<endl; } return 0; }