Implement strStr() [LeetCode] + KMP

本文介绍了一种使用KMP算法优化字符串匹配过程的方法,通过对比简单粗暴法,KMP算法能够显著提高strStr()函数的执行效率。文章提供了具体的C++实现代码。

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;  
}  
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值