码迷,mamicode.com
首页 > 其他好文 > 详细

C字符串经典

时间:2015-04-25 22:50:44      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:字符串

POJ1226——Substrings

题意,给定一堆字符串,找出最大的公共子串。

//Date:     2015.04.25
//Time:     0ms
//Memory:   144k

#include <cstdio>
#include <cstring>
using namespace std;

const int MAX_LEN=105;
int n,index,length;
char str[100][MAX_LEN];

void rev(char source[]){	//strrev()在POJ上编译无法通过
    char c;
    int i,j=strlen(source)-1;
    for(i=0;i<j;i++){
        c=source[i];
        source[i]=source[j];
        source[j--]=c;
    }
}

int SubString(){
    bool found;
    int SubLen,i,j;
    char sub_string[MAX_LEN],rev_sub_string[MAX_LEN];
    for(SubLen=length;SubLen;SubLen--){
        for(i=0;i<=length-SubLen;i++){
            strncpy(sub_string,str[index]+i,SubLen);
            strncpy(rev_sub_string,str[index]+i,SubLen);
            sub_string[SubLen]=rev_sub_string[SubLen]='\0';
            rev(rev_sub_string);
            found=true;
            for(j=0;j<n;j++){
                if( (strstr(str[j],sub_string)==NULL) && (strstr(str[j],rev_sub_string)==NULL) ){
                    found=false;
                    break;
                }
            }
            if(found)
                return SubLen;
        }
    }
    return 0;
}

int main(){
    int t,i,temp;
    scanf("%d",&t);
    while(t--){
        length=105;
        scanf("%d",&n);
        getchar();
        for(i=0;i<n;i++){
            gets(str[i]);
            temp=strlen(str[i]);
            if(length>temp){
                length=temp;
                index=i;
            }
        }
        printf("%d\n",SubString());
    }
    return 0;
}

C字符串经典

标签:字符串

原文地址:http://blog.csdn.net/zhangmh93425/article/details/45274425

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!