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

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

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

暴力解,时间复杂度O(N^3),空间复杂度O(1)

#include <algorithm>

using namespace std;

int main() {
    string str1,str2;
    while(cin>>str1>>str2){
        int m = str1.size();
        int n = str2.size();
        if(m>n){
        swap(str1, str2);
        m = str1.size();
        n = str2.size();
        }
        int len = 0,maxlen = -1,start = 0;
        for(int i =0;i<m;i++){
            
            for(int j = 0;j<n;j++){
                int tempi =i,temj=j;
                while(str1[tempi]==str2[temj]){
                    tempi++;
                    temj++;
                    len++;
                }
                if(len>maxlen){
                    maxlen = len;
                    start = i;
                }
                len = 0;
            }
        }
        
        string out = str1.substr(start,maxlen);
        cout<<out<<endl;
    }
}
全部评论

相关推荐

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