力扣28-实现strStr()——字符串匹配KMP算法

题目描述

实现 strStr() 函数。

给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

解题思路

这道题目可以用暴力求解的方式进行,但是考察的应该是KMP字符串匹配问题。

KMP主要思想是找到一个next数组,通过求解出next数组,方便我们对比原字符串和目的字符串。

卡哥哔站视频讲得不错,KMP原理直接看大佬的题解就行,此类题型可能得多连才能熟悉。

力扣——多图预警详解 KMP 算法icon-default.png?t=M666https://leetcode.cn/problems/implement-strstr/solution/duo-tu-yu-jing-xiang-jie-kmp-suan-fa-by-w3c9c/

输入输出示例

力扣28-实现strStr()——字符串匹配KMP算法_第1张图片

 

代码

class Solution {
    public int strStr(String haystack, String needle) {
        int haystackLength = haystack.length();
        int needleLength = needle.length();
        if(needleLength == 0) return 0; // 当needle是空字符串时,返回0
        int[] next = new int[needleLength];
        // 计算next数组
        for(int left = 0, right = 1; right < needleLength; right++){
            while(left>0 && needle.charAt(left) != needle.charAt(right)){
                // 在for循环中初始化指针right为1,left=0,开始计算next数组,right始终在left指针的后面
                left = next[left -1]; // 进行回退操作
            }
            if(needle.charAt(left) == needle.charAt(right)){
                left++;
            }
            next[right] = left;
        }

        for(int i = 0, j = 0; i < haystackLength; i++){
            while(j>0 && haystack.charAt(i) != needle.charAt(j)){
                j = next[j -1];
            }
            if(haystack.charAt(i) == needle.charAt(j)){
                j++;
            }
            // 返回当前在文本串匹配模式串的位置i减去模式串的长度,就是文本串字符串中出现模式串的第一个位置
            if(j == needleLength) return i - j + 1;
        }
        return -1;
    }
}

你可能感兴趣的:(从暴力搜索开始!,leetcode,算法)