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数组怎么求

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`string::find_first_of()` 是 C++ 中 `std::string` 类的成员函数,用于在字符串中查找第一个匹配指定字符集中任一字符的位置。 该函数的语法如下: ```cpp size_t find_first_of(const string& str, size_t pos = 0) const noexcept; size_t find_first_of(const char* s, size_t pos = 0) const noexcept; size_t find_first_of(const char* s, size_t pos, size_t count) const noexcept; size_t find_first_of(char c, size_t pos = 0) const noexcept; ``` 参数说明: - `str`:要搜索的字符串。 - `s`:要搜索的 C 风格字符串。 - `pos`:搜索的起始位置,默认为 0。 - `count`:要搜索的 C 风格字符串的字符数。 - `c`:要搜索的单个字符。 返回值: - 如果找到匹配字符,则返回第一个匹配字符的位置。 - 如果未找到匹配字符,则返回 `string::npos`。 示例用法: ```cpp #include <iostream> #include <string> int main() { std::string str = "Hello, world!"; size_t found = str.find_first_of("el", 0); if (found != std::string::npos) { std::cout << "First occurrence of 'e' or 'l' is at position " << found << std::endl; } else { std::cout << "No occurrence of 'e' or 'l' found." << std::endl; } return 0; } ``` 输出结果: ``` First occurrence of 'e' or 'l' is at position 1 ``` 在上述示例中,`find_first_of()` 函数用于查找字符串 `str` 中第一个匹配字符集 "el" 中的字符的位置。由于字符 'e' 在位置 1 处首次出现,因此返回值为 1。 注意:`find_first_of()` 函数还有一个重载版本,可以接受一个 `std::initializer_list<char>` 参数,用于指定要搜索的字符集。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值