题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <iostream> #include <string> using namespace std; int main() { string input1,input2; string LongStr,ShortStr; getline(cin, input1);getline(cin, input2); if(input1.size()<input2.size()){ ShortStr = input1; LongStr = input2; }else{ ShortStr = input2; LongStr = input1; }//因为输入没分长短,所以提前分好,下面可以根据短字符串来遍历 int maxlen = 0; int startIndex = -1; for(int i=0;i<ShortStr.size();i++){ for(int len =1;i+len<=ShortStr.size();len++){ string substr = ShortStr.substr(i,len); if(LongStr.find(substr)!=string::npos){ if(len>maxlen){ maxlen = len; startIndex = i; }//在长串中寻找是否有相同子串,如果有就更新长度和起始下标 } } } cout<<ShortStr.substr(startIndex,maxlen)<<endl; return 0; } // 64 位输出请用 printf("%lld")