[LeetCode] Implement strStr()

本文介绍了一种使用KMP算法实现字符串匹配的方法。通过C++代码详细展示了如何寻找一个字符串(needle)在另一个字符串(haystack)中首次出现的位置。如果找到则返回该位置的指针,否则返回null。代码中包含了初始化KMP前缀表的过程以及核心匹配逻辑。

Implement strStr():

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.


KMP是基本功啊!但还是一下init里有个地方写错,牢记啊牢记!!

class Solution {
public:
    char *strStr(char *hay, char *need) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if ( !hay || !need  )
	    	return NULL;
	    int nH=strlen(hay);
	    int nN=strlen(need);
	    if ( nN >nH )
		    return NULL;
	    if (nN==0)
		    return hay;

	    vector<int> pre(nN,-1);
	    init(pre,need,nN);
	    int pN=-1;
	    for(int pH=-1;pH<nH;pH++)
	    {
		    while(pN!=-1&&hay[pH+1]!=need[pN+1])
			    pN=pre[pN];
		    if(hay[pH+1]==need[pN+1])
			    pN++;
		    if ( pN == nN-1 )
			    return &hay[pH-nN+2];
	    }
	    return NULL;
    }
    void init(vector<int>& pre,char* s,int n)
    {
	    int p;
	    pre[0]=-1;
	    for(int i=1;i<n;i++)
	    {
		    p=pre[i-1];
		    while(p!=-1&&s[p+1]!=s[i])
			    p=pre[p];
		    if ( s[p+1]==s[i])
			    pre[i]=p+1;
		    else
			    pre[i]=-1;
	    }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值