Implement strStr()
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution { public: int strStr(char *haystack, char *needle) { if(!*needle) return 0; char *p1=haystack; char *p2; char *p1_advance=haystack;//此值用于保证haystack的剩余长度大于needle char *p1_old=haystack; p2=needle+1;//注意此处的初始值 while(*p2!='\0'){ p1_advance++; p2++; } for(;*p1_advance!='\0';p1_advance++){ p1=p1_old;//从上次遍历起始位置的下一个字符开始 p2=needle; while(*p1!='\0'&&*p2!='\0'&&*p1==*p2){ p1++; p2++; } if(*p2=='\0')return p1_old-haystack;//如果needle遍历完,说明匹配成功,可返回 p1_old++; } return -1; } };
此为暴力法,复杂度O(m*n),空间复杂度为O(1)。另有KMP解法,通过计算部分匹配表优化。时间复杂度可优化为O(N+M)