算法-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;
    }
相关推荐
对许21 分钟前
Java操作Excel最佳实践
java·spark·excel
高级程序源28 分钟前
springboot学生档案信息管理系统-计算机毕业设计源码96509
java·spring boot·spring·eclipse·mybatis·idea
yannan201903131 小时前
【算法】(C语言):二分查找
c语言·算法
zhangbin_2371 小时前
【Python机器学习】处理文本数据——将文本数据表示为词袋
人工智能·python·算法·机器学习·分类
martian6651 小时前
学懂C#编程:属性(Property)的概念定义及使用详解
java·开发语言·c#·属性·property
孑渡1 小时前
【LeetCode】每日一题:跳跃游戏
python·算法·leetcode·游戏·职场和发展
liulanba1 小时前
leetcode--二叉树中的最长交错路径
linux·算法·leetcode
Puppet__1 小时前
【康复学习--LeetCode每日一题】3115. 质数的最大距离
学习·算法·leetcode
阿亮说技术1 小时前
Java毕业设计 基于SSM vue电影院票务系统小程序 微信小程序
java·微信小程序·毕业设计·课程设计
dc爱傲雪和技术1 小时前
卡尔曼滤波Q和R怎么调
python·算法·r语言