Implement strStr()

本文介绍了一种使用KMP算法实现字符串匹配的方法。通过计算前缀表并利用该表进行高效匹配,找到目标子串在主串中的首次出现位置。文章提供了详细的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:
    void computePrefix(char* needle, int* next)
    {
        int m = strlen(needle);
        int i = 0, j = -1;
        next[0] = -1;
        while(needle[i] != '\0')
        {
            while (j >= 0 && needle[j] != needle[i])
            {
                j = next[j];
            }       
            ++i, ++j;
            next[i] = j;
        }        
    }    
    char *strStr(char *haystack, char *needle) {
        if (strcmp(haystack, needle) == 0)
        {
            return haystack;
        }    
        int m = strlen(needle);
        int n = strlen(haystack);
        if (m == 0)
        {
            return haystack;
        }    
        int next[m];
        int i = 0, j = 0;
        computePrefix(needle, next);
        while(haystack[i] != '\0')
        {
            while(j >= 0 && haystack[i] != needle[j])
             j = next[j];
            ++i, ++j;
            if (needle[j] == '\0')
            {
                return haystack + i - j;
            }        
        }        
        return NULL;    
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值