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

本题涉及到使用kmp算法,对字符串进行模式匹配,kmp算法可以参考代码随想录-kmp算法

代码如下:

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

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

        return -1;
    }

    vector<int> getNext(string& s){
        int j = 0;
        vector<int> next(s.size());
        for(int i = 1; i < s.size(); i++){
            while(j > 0 && s[i] != s[j]){
                j = next[j - 1];
            }

            if(s[i] == s[j]){
                j++;
            }

            next[i] = j;
        }

        return next;
    }
};
相关推荐
有点。9 小时前
C++广度优先搜索(二)-练习题
c++·算法·宽度优先
疯狂打码的少年10 小时前
【数据结构】队列的应用:循环队列
数据结构·笔记·算法
evans在进步10 小时前
LeetCode 17:电话号码的字母组合——Java DFS 回溯法详解
java·leetcode·深度优先
Winner_hwx10 小时前
python拓展
算法
TAN-90°-10 小时前
Deep Learning for Computer Vision——Image Classification with Linear Classifiers
python·深度学习·算法·计算机视觉·线性回归
阿pin10 小时前
Java随笔-红黑树
java·python·算法·红黑树
Hi李耶10 小时前
【LeetCode】17.电话号码的字母组合
算法·leetcode·职场和发展
江畔柳前堤19 小时前
大语言模型分布式训练:从并行策略到万卡工程的系统梳理
人工智能·分布式·深度学习·算法·目标检测·机器学习·语言模型
Doraemomo19 小时前
数据结构-环形链表
java·数据结构·链表
Forever Nore20 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode