strStr
1 class Solution { 2 public: 3 void get_nextval(const char *T, int next[]) 4 { 5 // 求模式串T的next函数值并存入数组 next。 6 int j = 0, k = -1; 7 next[0] = -1; 8 while ( T[j] != '\0' ) 9 { 10 if (k == -1 || T[j] == T[k]) 11 { 12 ++j; ++k; 13 if (T[j]!=T[k]) 14 next[j] = k; 15 else 16 next[j] = next[k]; 17 }// if 18 else 19 k = next[k]; 20 }// while 21 22 }// get_nextval 23 char *strStr(char *haystack, char *needle) { 24 // Start typing your C/C++ solution below 25 // DO NOT write int main() function 26 if( !needle || *needle == '\0' ) return haystack; 27 if( !haystack || *haystack =='\0' ) return NULL; 28 int len=0; 29 const char * c=needle; 30 while(*c++!='\0')//移动指针比移动下标快。 31 { 32 ++len;//字符串长度。 33 } 34 int *next=new int[len+1]; 35 get_nextval(needle,next); 36 int index=0,i=0,j=0; 37 while(haystack[i]!='\0' && needle[j]!='\0' ) 38 { 39 if(haystack[i]== needle[j]) 40 { 41 ++i;// 继续比较后继字符 42 ++j; 43 } 44 else 45 { 46 index += j-next[j]; 47 if(next[j]!=-1) 48 j=next[j];// 模式串向右移动 49 else 50 { 51 j=0; 52 ++i; 53 } 54 } 55 }//while 56 57 delete []next; 58 if(needle[j]=='\0') 59 return haystack + index;// 匹配成功 60 else 61 return NULL; 62 } 63 };
posted on 2013-09-04 14:46 jumping_grass 阅读(182) 评论(0) 收藏 举报
浙公网安备 33010602011771号