Implement strStr()

本文介绍如何实现strStr()函数,该函数用于在给定的字符串中查找指定子串的第一个出现位置,若未找到则返回-1。提供暴力法和KMP算法的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

每日算法——leetcode系列


问题 Implement strStr()

Difficulty: Easy

Implement strStr().

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

class Solution {
public:
    int strStr(string haystack, string needle) {

    }
};

翻译

实现strStr()

难度系数:简单

实现strStr()。
返回匹配时的第一个索引, 如果没有匹配的就返回-1。(感觉原文用针和草堆来形容带诙谐)

思路

strstr
经典题。

假设:
遍历到的needle索引为j, haystack索引为i+j, needle,haystack长度分别为m,n
- 暴力法
遍历haystack和needle,如果haystack[i+j] == needle[j](匹配), 则 j++;
如果不等于(失配),i++, j = 0 T(O) = m * n
- KMP
这个得专门写一篇总结的文章。
还有Linux的grep, BM算法

代码

class Solution {
public:
    int strStr(string haystack, string needle) {
        return strStrKMP(haystack, needle);
    }
private:
    // brute-force
    int strStrBF(string haystack, string needle) {

        if (needle.empty()){
            return 0;
        }
        int i = 0;
        int hSize =  (int)(haystack.size());
        int nSize = (int)(needle.size());
        if (hSize < nSize){
            return -1;
        }
        while(i < hSize){
            int j = 0;
            if (haystack[i + j] == needle[j]){
                j++;
            }else{
                i++;
                j = 0;
            }
            if (j >= nSize){
                return i;
            }
        }
        return -1;
    }

    // KMP
    int strStrKMP(string haystack, string needle) {

        if (needle.empty()){
            return 0;
        }
        int i = 0;
        int hSize = static_cast<int>(haystack.size());
        int nSize = static_cast<int>(needle.size());
        if (hSize < nSize){
            return -1;
        }
        vector<int> next(nSize, -1);
        calcNext(needle, next);
        int j = 0;
        while (i < hSize) {
            if (j == -1 || haystack[i] == needle[j]){
                i++;
                j++;
            }else{
                j = next[j];
            }
            if (j >= nSize){
                return i - nSize;
            }
        }
        return -1;
    }

    void calcNext(const string& needle, vector<int> &next){
        int nSize = static_cast<int>(needle.size());
        int i = 0;
        int j = -1;
        while (i < nSize - 1) {
            if (j == -1 || needle[i] == needle[j]){
                i++;
                j++;
                next[i] = j;
            }else{
                j = next[j];
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值