题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

#include <bits/stdc++.h>
using namespace std;

int main() {
    string str1, str2;
    getline(cin, str1);
    getline(cin, str2);
    int temp;
    string word_temp = "";
    int len = 0;
    string word = "";
    int len1 = str1.size();
    int len2 = str2.size();
    string str3;
    if(len1>len2){str3=str2; str2=str1; str1=str3;}
    len1 = str1.size();
    len2 = str2.size();
    for(int i=0; i<len1; i++){
        for(int j=0; j<len2; j++){
            temp = 0;
            word_temp = "";
            if(str1[i] == str2[j]){
                temp += 1;
                word_temp += str1[i];
                int step=min(len1-i,len2-j);
                
                    for(int k=1; k<step; k++){
                        if(str1[i+k]==str2[j+k]){temp += 1; word_temp += str1[i+k];}
                        else break;
                    }
                
            }
            if(len<temp){
                len = temp;
                word = word_temp;
            }
        }
    }
    cout << word;
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务