LeetCode 之 Implement strStr() — C 实现

本文介绍了如何用C语言实现LeetCode上的Implement strStr()问题,该函数旨在找到字串在字符串中首次出现的位置,若未找到则返回-1。解析中提到可以逐个字符比较,或者应用KMP算法来提高效率。

Implement strStr()

 

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

实现 strStr().

返回字串在字符串中第一次出现的位置,不存在则返回-1.

分析:

逐个字符比较,当字符串中剩下未被检索的字符串长度小于字串长度时就可停止检索。也可以使用 KMP 算法。

int strStr(char* haystack, char* needle) {
    char *pstartHay = haystack, *pt = NULL;
    char *pneedle = needle;
    int haylen = 0, needlen = 0;
    
    if(!haystack || !needle)/*空指针*/
        return -1;
    
    haylen = strlen(haystack);
    needlen = strlen(needle);
    if(haylen < needlen)/*待找字符串长度大于被找字符串*/
    {
        return -1;
    }
    
    while((haystack + haylen - pstartHay) >= needlen) /*还未匹配的字符串要大于待匹配字符串*/
    {
        pt = pstartHay;
        pneedle = needle;
        while(*pneedle)
        {
            if(*pt != *pneedle) /*存在不匹配字符,不再比较*/
                break;
            ++pt;
            ++pneedle;
        }
        if(!*pneedle) /*完全匹配*/
        {
            return (pstartHay - haystack);
        }
        
        ++pstartHay;
    }
    
    return -1;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值