2021.1.27 刷题(KMP字符串匹配)

题目链接:https://leetcode-cn.com/problems/implement-strstr
题目描述:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2

示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1

解题:

class Solution {
public:
    
    //求最长公共前后缀表
    vector<int> prefix_table(string pattern, int n)
    {
        vector<int> prefix(n, 0);
        int j = 0; //前缀指针
         for(int i = 1; i < n; i++)  //后缀指针
         {
            while (j - 1 >= 0 && pattern[j] != pattern[i]){
                j = prefix[j - 1];//最前缀指针跳动
            }
            if(pattern[j] == pattern[i]){
                j++;
                prefix[i] = j;
            }
        }
        return prefix;
    }


    // //prefix表右移一位,得next表
    // void next(vector<int> prefix, int n) 
    // {
    //     for(int i = n - 1; i > 0; i--)
    //     {
    //         prefix[i] = prefix[i - 1];
    //     }
    //     prefix[0] = -1;
    // }

    int strStr(string haystack, string needle) {
        int haystack_len = haystack.size();
        int needle_len = needle.size();
        vector<int> next;
        //特判
        if(needle_len == 0)
            return 0;
        if(haystack_len < needle_len)
            return -1;
        next = prefix_table(needle, needle_len);
        int i = 0; //i指向主串的指针
        int j = 0; //j指向模式串的指针

        for(i; i < haystack_len; i++)
        {
            while(j - 1 >= 0 && haystack[i] != needle[j])
            {
                j = next[j - 1]; //回退
            }
            if(haystack[i] == needle[j])
            {
                j++;
                if(j == needle_len)
                {
                    return i - needle_len + 1;
                }
            }
        }

        return -1;

    }
};
原文地址:https://www.cnblogs.com/ZigHello/p/14336335.html