Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
实现了下,KMP算法明显速度提高一倍了

简单粗暴法:
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if (haystack == NULL || needle == NULL)
return NULL;
int hay_len = strlen(haystack);
int need_len = strlen(needle);
if(need_len > hay_len) return NULL;
for(int i=0;i<=hay_len-need_len;++i){
int j = 0;
for(; j<need_len; ++j){
if(haystack[i+j] != needle[j])
break;
}
if(j == need_len)
return haystack + i;
}
return NULL;
}
};
KMP算法:具体思路见 July-KMP算法之总结篇(12.09修订,必懂KMP)
class Solution {
public:
char *strStr(char *haystack, char *needle) {
if(haystack == NULL || needle == NULL) return NULL;
if(haystack == ""){
if(needle == "") return "";
else return NULL;
}
return kmp_find(haystack,needle);
}
char *kmp_find( char *target, char *pattern)
{
const int target_length=strlen(target);
const int pattern_length=strlen(pattern);
int* overlay_value=new int[pattern_length];
overlay_value[0]=-1; //remember:next array's first number was -1.
int index=0;
//next array
for (int i=1;i<pattern_length;++i)
//注,此处的i是从1开始的
{
index=overlay_value[i-1];
while (index>=0 && pattern[index+1]!=pattern[i])
{
index=overlay_value[index];
}
if(pattern[index+1] == pattern[i])
{
overlay_value[i]=index+1;
}
else
{
overlay_value[i]=-1;
}
}
//mach algorithm start
int pattern_index=0;
int target_index=0;
while (pattern_index<pattern_length && target_index<target_length)
{
if (target[target_index] == pattern[pattern_index])
{
++target_index;
++pattern_index;
}
else if(pattern_index==0)
{
++target_index;
}
else
{
pattern_index=overlay_value[pattern_index-1]+1;
}
}
if (pattern_index==pattern_length)
{
return target+ target_index-pattern_index;
}
else
{
return NULL;
}
delete [] overlay_value;
}
};
本文介绍了一种使用KMP算法优化字符串匹配过程的方法,通过对比简单粗暴法,KMP算法能够显著提高strStr()函数的执行效率。文章提供了具体的C++实现代码。


被折叠的 条评论
为什么被折叠?



