Chinaunix首页 | 论坛 | 博客
  • 博客访问: 335587
  • 博文数量: 82
  • 博客积分: 2602
  • 博客等级: 少校
  • 技术积分: 660
  • 用 户 组: 普通用户
  • 注册时间: 2007-08-10 08:48
文章分类

全部博文(82)

文章存档

2008年(17)

2007年(65)

分类: C/C++

2007-09-03 08:30:41

作为最原始的字符串匹配算法,它的时间复杂度是O((n-m+1)m)

#include "stdio.h"

//计算字符串的长度

int Length(char *s)
{
 int count=0;
 while(*s++!='\0')
  count++;

 return count;
}

//字符串匹配

void NaiveStringMatching(char *t,char *p)
{
 int n=Length(t);
 int m=Length(p);
 if(n<m)
 {
  printf("Error:The P is longer than T!\n");
  return;
 }

 bool find=true;

 printf("The string T is %s\n",t);
 printf("The string P is %s\n",p);
 for(int s=0;s<=n-m;s++)
 {
  find=true;
  for(int i=0;i<m;i++)
  {
   if(t[s+i]!=p[i])
   {
    find=false;
    break;
   }
  }
  if(find)
   printf("Pattern occurs with shift:%d\n",s+1);
 }
}

int main()
{
 char t[]="abcdebcg";
 char p[]="bcdebcg";

 NaiveStringMatching(t,p);
 return 0;
}

阅读(2975) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~