题解 | #查找两个字符串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;
    }
}
全部评论

相关推荐

06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务