算法-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;
    }
相关推荐
.道阻且长.5 小时前
2.LeetCode算法习题讲解--双指针--复写零
算法·leetcode·职场和发展
·薯条大王5 小时前
经济实惠玩云服务器|一台云服务器多人共用,子账号配置教程
java·linux·运维·服务器·汇编·c++·python
To_OC7 小时前
LC 438 找到所有字母异位词:暴力超时后,我靠滑动窗口一招搞定
javascript·算法·leetcode
ZJH__GO8 小时前
网络编程v4pro--实现聊天室文件传输功能
java·服务器·网络·计算机网络
程序员黑豆8 小时前
Windows 系统 Java 环境变量配置全攻略:解决“不是内部或外部命令”
java·前端·ai编程
命运之光9 小时前
【C语言完整代码】就诊信息管理系统
java·c语言·开发语言
凤山老林9 小时前
Spring Boot @Async 线上实战:从默认配置到生产级线程池治理
java·spring boot·后端
Forever Nore9 小时前
学完C语言力扣第一题做不来正常吗
数据结构·算法
marvelyu10 小时前
每天10分钟学会OceanBase系列(Day 20):跨机房容灾实战——构建多数据中心高可用架构
java·大数据·数据库