LeetCode-Implement strStr()

实现KMP算法解决字符串匹配问题
本文详细阐述了KMP算法的实现过程,通过构建next数组和利用模式串前缀后缀特性,高效地在主字符串中查找模式串首次出现的位置。包括算法原理、代码实现及实例演示。

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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(haystack==NULL||needle==NULL)return NULL;
        if(needle[0]=='\0')return haystack;
        int len=0;
        for(;;){if(needle[len]=='\0')break;len++;}
        vector<int> dict;
        dict.resize(len);
        dict[0]=-1;
        dict[1]=0;
        for(int i=2;i<len;i++){
            int j=dict[i-1];
            while(j>=0&&needle[j]!=needle[i-1]){
                j=dict[j];
            }
            if(j<0)j=0;
            else if(needle[j]==needle[i-1]){
                j++;
            }
            dict[i]=j;
        }
        int i=0,j=0;
        while(haystack[i]!='\0')
        {
            while(j>=0&&haystack[i]!=needle[j]){
                j=dict[j];
            }
            j++;
            if(j==len){
                return &haystack[i-len+1];
            }
            i++;
        }
        return NULL;
    }
};

 

转载于:https://www.cnblogs.com/superzrx/p/3332378.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值