题目描述
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
分析:直接暴力求解,时间复杂度为O(mn)
class Solution {
public:
char *strStr(char *haystack, char *needle)
{
int m = strlen(haystack),n = strlen(needle);
if(m<n) return nullptr;
int diff = m-n+1;
for(int start=0;start<diff;start++)
{
int j=0;
for(;j<n;j++)
{
if(haystack[start+j] != needle[j])
break;
}
if(j==n)
{
return haystack+start;
}
}
return nullptr;
}
};
这道题也可以用KMP算法,将复杂度降低为O(m+n)
具体实现就不在展开了,具体可以参考:
http://blog.csdn.net/qq_26437925/article/details/52135791
http://blog.csdn.net/hcbbt/article/details/44099749
讲解kmp算法的可以参考: