LeetCode28.实现StrStr()/找出字符串中第一个匹配项的下标

本文介绍了如何在LeetCode题目28中使用暴力解法和KMP算法解决字符串haystack中查找needle第一次出现的下标问题。暴力解法逐字符对比,而KMP算法利用预处理的next数组提高效率。
摘要由CSDN通过智能技术生成

Question

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。

Example

Example 1:

输入:haystack = "sadbutsad", needle = "sad"
输出:0
解释:"sad" 在下标 0 和 6 处匹配。
第一个匹配项的下标是 0 ,所以返回 0 

Example 2:

输入:haystack = "leetcode", needle = "leeto"
输出:-1
解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。

Idea

  • 1 <= haystack.length, needle.length <= 104
  • haystackneedle 仅由小写英文字符组成

Solution1:暴力解法

class Solution {
public:
    int strStr(string haystack, string needle) {
        int ln = needle.size(), lh = haystack.size();
        for(int i = 0; i < lh; i++){
            for(int j = 0; j < ln; j++){
                if(haystack[i+j] != needle[j])break;
                else if(j >= ln - 1) return i;
            }
        }
        return -1;
    }
};

Solution2:KMP算法

class Solution {
public:
    int *buildNext(string p){
        int m = p.size(), j = 0;
        int *N = new int[m];
        int t = N[0] = -1;

        while(j < m-1){
            if(t < 0 || p[t] == p[j]){
                t++;j++;
                N[j] = t; // 每次求N[j], 后面t = N[t]肯定是有值的
            }else{
                t = N[t]; // j > t
            }
        }
        
        return N;
    }
    int strStr(string haystack, string needle) {
        int *next = buildNext(needle);
        int m = haystack.size(), i = 0;
        int n = needle.size(), j = 0;

        while(j < n && i < m){
            if(0 > j || haystack[i] == needle[j]){
                i++;j++;
            }else{
                j = next[j];
            }
        }

        delete [] next;

        if(j == n) return i-j;
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xの哲學

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值