28. Find the Index of the First Occurrence in a String

Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "sadbutsad", needle = "sad"
Output: 0
Explanation: "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

Example 2:

Input: haystack = "leetcode", needle = "leeto"
Output: -1
Explanation: "leeto" did not occur in "leetcode", so we return -1.

Constraints:

  • 1 <= haystack.length, needle.length <= 104
  • haystack and needle consist of only lowercase English characters.
class Solution {
public:
    void getNext(string &s,int *next){
        int j=0;
        next[0]=0;
        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;
        }
    }
    int strStr(string haystack, string needle) {
        if(needle.size()==0)return 0;
        int j=0;
        vector<int>next(needle.size());
        getNext(needle,&next[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;
    }
};

注意:

        1.前缀表是什么?为什么要这样用——KMP算法

        2.Next数组怎么求

相关推荐

  1. 周报 | 24.4.22-24.4.28文章汇总

    2024-07-22 13:12:04       29 阅读
  2. 管理篇 - 2428

    2024-07-22 13:12:04       42 阅读
  3. 12.28

    2024-07-22 13:12:04       55 阅读
  4. 面试经典150题(27-28)

    2024-07-22 13:12:04       52 阅读
  5. Ubuntu 22.04 安装cmake3.28

    2024-07-22 13:12:04       63 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-22 13:12:04       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-22 13:12:04       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-22 13:12:04       45 阅读
  4. Python语言-面向对象

    2024-07-22 13:12:04       55 阅读

热门阅读

  1. WSL 2 Oracle Linux 9.1 安装配置

    2024-07-22 13:12:04       19 阅读
  2. 项目进行到中后期,我发现开发改了代码

    2024-07-22 13:12:04       19 阅读
  3. OpenStack中nova的架构

    2024-07-22 13:12:04       14 阅读
  4. MCU常见相关术语缩写说明

    2024-07-22 13:12:04       13 阅读
  5. 【Statement对象】

    2024-07-22 13:12:04       18 阅读