问题描述:

给定两个字符串T, P。查找字符串P在字符串T中出现的次数。

解决方法:

典型的KMP算法的题目,在此使用的KMP算法为算法导论上介绍的算法。下一篇文章将详细介绍KMP算法的计算过程。

题目链接:

http://hihocoder.com/problemset/problem/1015

源代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define M 9999
#define N 999999
char t[N], p[M];
int *getprefix(char p[])
{
int *h, plen, k, i;
plen = strlen(p);
h = (int *)malloc(plen*sizeof(int));
h[0] = 0;
k=0;
for(i=1; i<plen; i++)
{
while(k>0 && p[k]!=p[i])
k=h[k-1];
if(p[k] == p[i])
k++;
h[i]=k; }
return h;
}
int kmp_matcher(char t[], char p[])
{
int count;
int *h, tlen, plen, i, q;
tlen = strlen(t);
plen = strlen(p);
h = getprefix(p);
count = 0;
q=0;
for(i=0; i<tlen; i++)
{
while(q>0 && t[i]!=p[q])
q = h[q-1];
if(t[i] == p[q])
q++;
if(plen == q)
{
count++; q = h[q-1];
}
}
return count;
}
int main()
{ int n, ans;
scanf("%d\n",&n);
while(n--)
{
gets(p); gets(t);
ans = kmp_matcher(t, p);
printf("%d\n", ans);
}
return 0;
}

最新文章

  1. svn报错:“Previous operation has not finished; run &#39;cleanup&#39; if it was interrupted“ 的解决方法
  2. 深入理解javascript--笔记
  3. 有关google的小问题
  4. 使用WPF动态生成Code 39条形码
  5. IO流(五)__文件的递归、Properties、打印流PrintStream与PrintWriter、序列流SequenceInputStream
  6. 6、软件配置工程师要阅读的书籍 - IT软件人员书籍系列文章
  7. HTML5 web Form表单验证实例
  8. oracle的冷备份
  9. pthread_t definition
  10. Ansible1:简介与基本安装【转】
  11. 从头认识Spring-2.7 自己主动检測Bean(2)-过滤器&amp;lt;context:include-filter/&amp;gt;
  12. IntelliJ IDEA 17和Maven构建javaWeb项目
  13. python基础语法、数据结构、字符编码、文件处理 练习题
  14. python 往mysql数据库中插入多条记录。
  15. c#devexpress 窗体控件dock的重要
  16. 1.Linux电源管理-休眠与唤醒
  17. XML Namespace (xmlns) 属性
  18. 安装windows系统时遇到的大坑——鼠标键盘没反应
  19. ArcGIS案例学习笔记-栅格数据分区统计(平均高程,污染浓度,污染总量,降水量)
  20. 如何整合Office Web Apps至自己开发的系统(二)

热门文章

  1. redmine配置邮件
  2. list转换为map
  3. 51nod 区间中第K大的数
  4. Lorenzo Von Matterhorn
  5. 核心动画 CAAnimation 进阶
  6. HDU 4287 Intelligent IME(字典树)
  7. ExtJS的4.1新特性简要介绍
  8. jQuery实现瀑布流(pc、移动通用)
  9. Lua学习笔记4. coroutine协同程序和文件I/O、错误处理
  10. H2最完整的资料下载地址: