九度 oj 题目1149:子串计算

62 篇文章 0 订阅
2 篇文章 0 订阅

http://ac.jobdu.com/problem.php?pid=1149

 含有两种解法 : kmp or 暴力

#include <stdio.h>
#include <cstring>
#include <algorithm>

typedef struct item{ 
    char s[102]; 
    int times;
    bool friend operator <  (struct item a, struct item b){ 
        return strcmp(a.s,b.s) < 0;  
    }  
} Item; 

int search(char substr[],char str[]){ 
    int subl = (int) strlen(substr);  
    int len = (int) strlen(str); 
    int i,j,k,t = 0;
    for ( i = 0; i < len-subl+1; ++i) { 
        for ( j = 0,k=i; j < subl; ++k, ++j) { 
            if(str[k] != substr[j]) break;  
        }  
        if(j == subl) t++; 
    } 
    return t;
} 

void getNext(char p[], int next[]){ 
    int j,k;
    next[0] = -1;
    j = 0;
    k = -1;
    int plen = (int) strlen(p);  
    while(j < plen - 1) { 
        if(k==-1 || p[j] == p[k]){ 
            ++j;
            ++k;
            next[j] = k; 
        }else{ 
            k = next[k]; 
        }    
    } 
}  

int KMPmatch(char substr[],char str[]){ 
    int times = 0;
    int next[102];
    int i,j;
    i = 0,j=0;
    getNext(substr,next); 
    int len =(int) strlen(str);  
    int subl = (int) strlen(substr);  
    while(i<len){ 
        if(j==-1||str[i] == substr[j]){ 
            i++;
            j++; 
        }else{ 
            j = next[j]; 
        }    
        if(j == subl ){ 
            times++;
            i = i-j+1;
            j=0;
        }  

    }  
    return times;
} 

int main(){ 
    char str[102];
    char substr[102];
    Item items[15000];
    int n=0;
    while(scanf("%s",str)!=EOF){ 
        n = 0;
        int len = (int) strlen(str);  
        for (int i = 0; i < len; ++i) { 
            for (int j = i; j <len; j++) { 
                strncpy(substr,str+i,(unsigned) (j-i+1)); 
                substr[j-i+1] = '\0';
                int times = KMPmatch(substr,str);
                //int times = search(substr,str);
                strcpy(items[n].s,substr);
                items[n++].times = times;
            }  
        } 
        std::sort(items,items+n);
        char pre[102]={'\0'};
        for (int i = 0; i < n; ++i) { 
            if(items[i].times > 1 && strcmp(items[i].s,pre)!=0){ 
              printf("%s %d\n",items[i].s,items[i].times);   
              strcpy(pre,items[i].s); 
            } 

        } 

    }   
}  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值