Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
思路:时间复杂度O(m*n),也就是BF(Brute Force)算法;
code:
class Solution { public: char *strStr(char *haystack, char *needle) { if(!*needle) return haystack; char *p,*q; char *p_advance=haystack; for(q=&needle[1];*q;++q) ++p_advance; for(p=haystack;*p_advance;++p_advance) { char *p_old=p; q=needle; while(*p&&*q&&*p==*q) { ++p; ++q; } if(!*q) return p_old; p=p_old+1; } return NULL; } };
此问题还有更经典的KMP算法;
code:
class Solution { public: char *strStr(char *haystack, char *needle) { if(!*needle) return haystack; int *next=new int[strlen(needle)]; getNext(needle,next); for(int i=0,j=0;i<strlen(haystack);) { if(j==-1||haystack[i]==needle[j]) { ++i; ++j; } else j=next[j]; if(j==strlen(needle)) return (char*)(i-strlen(needle)+haystack); } return NULL; } //array of next //as for char *s="ababa",the corresponding array is:-1,0,0,1,2 void getNext(char *needle,int next[]) { next[0]=-1; int k=-1; int j=0; while(j<strlen(needle)-1) { if(k==-1||needle[j]==needle[k]) { ++j; ++k; next[j]=k; } else k=next[k]; } } };
KMP算法参考:
时间: 2024-11-05 18:51:10