zoukankan      html  css  js  c++  java
  • Substrings

    题目大意:给你N个串,求出来他们的最大公共子串的长度(子串反过来也算他们的子串)。
     
    分析:很久以前就做过这道题,当时是用的strstr做的,不过相同的都是枚举了子串......还是很暴力,希望下次遇到类似的题目我已经掌握高效的方法了。
    ==============================================================================
    #include<stdio.h>
    #include<string.h>
    
    const int MAXN = 107;
    const int oo = 1e9+7;
    const int mod = 10007;
    
    char s[MAXN][MAXN];
    int next[MAXN];
    
    void GetNext(char s[], int N)
    {
        int i=0, j=-1;
        next[0] = -1;
    
        while(i < N)
        {
            if(j==-1 || s[i]==s[j])
                next[++i] = ++j;
            else
                j = next[j];
        }
    }
    bool KMP(char a[], char b[])
    {
        int i=0, j=0;
        int Na = strlen(a);
        int Nb = strlen(b);
    
        GetNext(b, Nb);
    
        while(i < Na)
        {
            while(j==-1 || (a[i]==b[j] && i<Na))
                i++, j++;
            if(j == Nb)return true;
    
            j = next[j];
        }
    
        return false;
    }
    bool OK(char a[], char s[])
    {
        if(KMP(a, s) == true)
            return true;
        strrev(s);
    
        return KMP(a, s);
    }
    int main()
    {
        int T;
    
        scanf("%d", &T);
    
        while(T--)
        {
            int i, j, k, N, len=oo, ans=0;
            char a[MAXN];///保存最短的那个串
    
            scanf("%d", &N);
    
            for(i=1; i<=N; i++)
            {
                scanf("%s", s[i]);
    
                int M = strlen(s[i]);
    
                if(len > M)
                {
                    len = M;
                    strcpy(a, s[i]);
                }
            }
    
            for(i=1; i<=len; i++)
            for(j=0; i+j<=len; j++)
            {
                char b[MAXN] = {0};
    
                strncpy(b, a+j, i);
    
                for(k=1; k<=N; k++)
                {
                    if(OK(s[k], b) == false)
                        break;
                }
    
                if(k > N)
                    j=len, ans = i;
            }
    
            printf("%d
    ", ans);
        }
    
        return 0;
    }
  • 相关阅读:
    Java IO 5 : 对象序列化
    Java IO 4 : RandomAccessFile
    3 Linux平台安装jenkins
    AWS-EC2配置swap
    2.8 环境准备-静态资源服务器搭建
    2.7 环境准备-MongoDB
    2.6 环境准备-redis
    2.5 环境准备-zookeeper
    2.4 环境准备-mysql8
    2.3 环境准备-nexus
  • 原文地址:https://www.cnblogs.com/liuxin13/p/4732767.html
Copyright © 2011-2022 走看看