算法-KMP算法

时间复杂度:

java 复制代码
public int strStr(String haystack, String needle) {
        int[] next = new int[needle.length()];
        //next数组的生成
        next[0] = 0;
        int prefixLen = 0;//共同前后缀长度
        int i = 1, j = 1;//i,j复用
        while (i < needle.length()) {
            if (needle.charAt(prefixLen) == needle.charAt(i)) {
                prefixLen++;
                next[j++] = prefixLen;
                i++;
            } else {
                if (prefixLen == 0) {
                    next[j++] = 0;
                    i++;
                } else {
                    prefixLen = next[prefixLen - 1];
                }
            }
        }

        i = j = 0;
        while (i < haystack.length()) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            } else if (j > 0) {
                j = next[j - 1];
            } else {
                i++;
            }
            if (j == needle.length())
                return i - j;
        }
        return -1;
    }
相关推荐
蜡笔小谢6 小时前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness
唐老板8 小时前
Spring AI 2.0 只支持 Boot 4
java
琳少_11 小时前
java程序设计笔记
java·开发语言·数据库·笔记
小荷才露尖尖角,早有蜻蜓立上头12 小时前
SpringBoot 定时任务
java·spring boot·后端
Helix25013 小时前
JDK高频报错速查手册:javac不是内部命令、内存溢出、版本不兼容等12类问题解决方法
java·开发语言·内存溢出·java异常处理·jdk版本兼容·jdk报错·javac报错
CoderYanger14 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
摇滚侠15 小时前
《On Java 中文版 基础卷》阅读笔记 接口 19
java·开发语言·笔记
吃我一窝jio16 小时前
Java多线程核心知识点梳理
java·开发语言·笔记
青少儿编程课堂17 小时前
蓝桥杯真题解析:三维偏序的CDQ分治(全国青少年信息素养大赛与电子学会编程考级)
c++·python·算法·bfs·信息学竞赛