Chinaunix首页 | 论坛 | 博客
  • 博客访问: 117329
  • 博文数量: 53
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-24 16:22
文章存档

2014年(53)

我的朋友

分类: C/C++

2014-10-07 15:30:17

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.


我试着用了最简单的匹配,居然过了,以后再用KMP之类的好好研究一下。


  1. char *strStr(char *haystack, char *needle) {
  2.         if(haystack==NULL || needle==NULL)
  3.             return NULL;
  4.         char * head=haystack;
  5.         
  6.         while(head!='\0'){
  7.             char *p0=head;
  8.             char * p=needle;
  9.             while(*p!='\0' && *p0!='\0'){
  10.                 if(*p!=*p0){
  11.                     break;
  12.                 }
  13.                 p++;
  14.                 p0++;
  15.             }
  16.             if(*p=='\0'){
  17.                 return head;
  18.             }
  19.             if(*p0=='\0'){
  20.                 return NULL;
  21.             }
  22.             head++;
  23.         }
  24.         return NULL;
  25.     }

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