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

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

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

#include <stdio.h>
#include <string.h>

int main() {
    
    char sht[310] = {0};
    char lon[310] = {0};

    gets(sht);
    gets(lon);
    if(strlen(sht) > strlen(lon))
    {
        char tmp[310] = {0};
        strcpy(tmp, lon);
        strcpy(lon, sht);
        strcpy(sht, tmp);
    }

    int sht_len = strlen(sht);
    int lon_len = strlen(lon);
    char *find = NULL;
    int maxlen = 0;
    int tmp = 0;
    int begin = 0;

    for(int i = 0; i < sht_len; ++ i)
    {
        //以sht[i]为首的子串
        for(int j = 0; j < lon_len; ++ j)
        {
            if(sht[i] == lon[j])
            {
                tmp = 1;
                for(int k = 1; sht[i+k] == lon[j+k]; ++ k)
                {
                    ++ tmp;
                }

                if(tmp > maxlen)
                {
                    maxlen = tmp;
                    begin = i;
                }
                
            }
        }
    }

    for(int i = 0; i < maxlen; ++ i)
    {
        putchar(sht[begin+i]);
    }

    return 0;
}

全部评论

相关推荐

阿里系笔试成绩互通吗?
投递阿里巴巴集团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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