KMP算法 leetcode-28

[leetcode 28题](https://leetcode-cn.com/problems/implement-strstr/)

实现 strStr() 函数。

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

 

说明:

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

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

 

示例 1:

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

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

输入:haystack = "", needle = ""
输出:0

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

复制代码
class Solution {
    public int strStr(String haystack, String needle) {
        int m = haystack.length();//i遍历
        int n =  needle.length();//j遍历
        if(needle.length()==0){
            return 0;
        }
        int[] prefix = prefix(needle);

        int i = 0;
        int j = 0;
        for(i = 0; i<m;i++){
            while(j>0&& needle.charAt(j) != haystack.charAt(i)){
                j = prefix[j-1];
            }
            
            if(needle.charAt(j) == haystack.charAt(i)){
                j++;
            }
            if(j == n){
                return i-n+1;
            }

            
        }
            return -1;
    }

    //计算模式串的前缀表
    private int[] prefix(String needle){
        int beforeEnd = 0;
        int[] prefix = new int[needle.length()];
        for(int afterEnd = 1; afterEnd<needle.length(); afterEnd++){
            while(beforeEnd > 0 && needle.charAt(beforeEnd)!=needle.charAt(afterEnd)){
                beforeEnd = prefix[beforeEnd-1];
            }
            if(needle.charAt(afterEnd) == needle.charAt(beforeEnd)){
                beforeEnd++;
            }
            prefix[afterEnd] = beforeEnd;
        }
        return prefix;
    }
}
复制代码

 

posted @   zhongweiLeex  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示