代码随想录算法训练营第九天| 28. 实现 strStr() 和讲讲KMP

**28. 实现 strStr() **
https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/

public void getNext(int[] next,String s){
        int j = -1;
        next[0] = j;
        for (int i = 1; i < s.length(); i++) {
            while (j >= 0 && s.charAt(i) != s.charAt(j+1)){
                j = next[j];
            }
            if (s.charAt(i) == s.charAt(j+1)){
                j++;
            }
            next[i] = j;
        }
    }
    public int strStr(String haystack, String needle) {
        int[] next = new int[needle.length()];
        getNext(next,needle);
        int j = -1;
        for (int i = 0; i < haystack.length(); i++) {
            while (j >= 0 && haystack.charAt(i) != needle.charAt(j+1)){
                j = next[j];
            }
            if (haystack.charAt(i) == needle.charAt(j+1)){
                j++;
            }
            if (j == needle.length() - 1){
                return i - j;
            }
        }
        return -1;
    }

总结:KMP 没什么好说的
讲讲KMP


总结:见到KMP的题就构造next数组再用next数组
构造的流程分别是:
          1、初始化(j自己定义,i走for循环,i从1开始,j从-1开始)。
          2、while判断前后缀不同时,向前回退。
          3、if判断前后缀相同时j++
          4、无论如何都要来一次next[i] = j。
用的流程是:
        1、初始化j去遍历B串,i走for循环(i从0开始,j从-1开始)。
        2、while判断不同时,j往前回退。
        3、if判断相同时,j++。
        4、if判断j走到B串的最后一位了,就说明在A中找到B了,这时按需返回相应的值或者执行相应的操作即可。

posted @   jeasonGo  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示