Hat’s Words

本文介绍了一种基于AC自动机的字符串匹配算法,并通过C语言实现了一个具体的例子。该算法能够高效地处理大量字符串的匹配问题,在文本搜索等领域有着广泛的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=1247

View Code
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 char c[50010][110] ;
 5 struct node
 6 {
 7     int flag ;
 8     struct node *next[26] ;
 9 };
10 struct node *creat()
11 {
12     int i ;
13     struct node *p ;
14     p = (struct node*)malloc(sizeof(struct node));
15     p->flag = 0 ;
16     for(i=0; i<26; i++)
17     p->next[i] = NULL ;
18     return p;
19 }
20 void insert(struct node *head, char *s)
21 {
22     int i ;
23     struct node *p = head ;
24     int len = strlen(s) ;
25     for(i=0; i<len; i++)
26     {
27         int t = s[i] - 'a' ;
28         if(p->next[t]==NULL)
29         {
30             p->next[t] = creat() ;
31         }
32         p = p->next[t] ;
33     }
34     p->flag = 1 ;
35 }
36 int judge(struct node *head, char *s)
37 {
38     struct node *p = head ;
39     for(; *s!='\0';)
40     {
41         int t = *s - 'a' ;
42         if(p->next[t]==NULL)
43         return 0 ;
44         p = p->next[t] ;
45         if(p->flag==1&&*(s+1)=='\0')
46         return 1 ;
47         s++ ;
48     }
49     return 0 ;
50 }
51 int search(struct node *head, char *s)
52 {
53     struct node *p = head ;
54     for(; *s!='\0';)
55     {
56         int t = *s - 'a' ;
57         if(p->next[t]==NULL)
58         return 0 ;
59         p = p->next[t] ;
60         if(p->flag==1&&judge(head, s+1))
61         {
62             return 1;
63         }
64         s++ ;
65     }
66     return 0 ;
67 }
68 int main()
69 {
70    int i = 0, j ;
71    struct node *head = creat() ;
72    while(gets(c[i])!=NULL)
73    {
74        insert(head, c[i]) ;
75        i++ ;
76    }
77    for(j=0; j<i; j++)
78    {
79        if(search(head,c[j]))
80        puts(c[j]) ;
81    }
82    return 0 ;
83 }

 

转载于:https://www.cnblogs.com/yelan/archive/2013/02/20/2919314.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值