力扣-字符串-28 找出字符串中第一个匹配项的下标

思路

kmp算法的练习,实际上来说在构建next数组和使用next数组都用到了前一位字符串的最长相等前后缀

代码

cpp 复制代码
class Solution {
public:
    void getNext(int *next, string s){
        int j = 0;
        next[0] = 0;
        for(int i = 1; i < s.size(); i++){
            while(j > 0 && s[j] != s[i]){
                j = next[j - 1];
            }
            if(s[j] == s[i]) j++;
            next[i] = j;
        }
    }

    int strStr(string haystack, string needle) {
        if(needle.size() == 0)
            return 0;
        
        vector<int> next(needle.size());
        getNext(&next[0], needle);

        int i = 0, j = 0;
        for(int i = 0; i < haystack.size(); i++){
            
            while(j>0 && needle[j] != haystack[i]){
                j = next[j-1];
            }

            if(needle[j] == haystack[i]) j++;


            if(j == needle.size()){
                return i - j + 1;
            }
        }

        return -1;

    }
};
相关推荐
非优秀程序员10 小时前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
文丑颜不良啊13 小时前
LeetCode2481~2500题目解析
java·leetcode
武子康17 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
文丑颜不良啊20 小时前
LeetCode2461~2480题目解析
java·leetcode
文丑颜不良啊21 小时前
LeetCode2441~2460题目解析
java·leetcode
文丑颜不良啊1 天前
LeetCode2521~2540题目解析
java·leetcode
lisw051 天前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术1 天前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs1 天前
Rust LeetCode238 算法题解
开发语言·算法·rust