【leetcode】3.2 Implement strStr()

【问题描述】
Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
实现strstr(). 返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回nullptr。
注:strstr()是c++中的一个函数

【暴力破解】
时间复杂度O(N*M), 空间复杂度 O(1)

#include<iostream>
using namespace std;
// Returns a pointer to the first occurrence of needle in haystack, 
// or null if needle is not part of haystack.
char *strStr(const char *haystack, const char *needle)
{
    if (!*needle)   return (char*)haystack;

    const char *p1;
    const char *p2;
    const char *p1_advance = haystack;

    for (p2 = &needle[1]; *p2; p2++)
        p1_advance++;

    for (p1 = haystack; *p1_advance; p1_advance++)
    {
        char *p1_old = (char *)p1;

        p2 = needle;
        while (*p1 && *p2 && *p1 == *p2)
        {
            p1++;
            p2++;
        }
        if (!*p2)   return p1_old;

        p1 = p1_old +1;
    }

    return NULL;
}

void main()
{
    char *haystack = "This a world!";
    char *needle = "world";
    int n = strStr(haystack, needle) - haystack;
    cout << "The place is :" << n << endl;

}

其实这段代码自己不熟悉的一个是空指针的判断 if (!*p2)
【KMP】
// 待完成

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值