算法-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;
    }
相关推荐
这儿有一堆花2 小时前
比特币:固若金汤的数字堡垒与它的四道防线
算法·区块链·哈希算法
BillKu2 小时前
Java + Spring Boot + Mybatis 实现批量插入
java·spring boot·mybatis
YuTaoShao2 小时前
Java八股文——集合「Map篇」
java
客卿1232 小时前
力扣100-移动0
算法·leetcode·职场和发展
有梦想的攻城狮4 小时前
maven中的maven-antrun-plugin插件详解
java·maven·插件·antrun
CM莫问5 小时前
<论文>(微软)WINA:用于加速大语言模型推理的权重感知神经元激活
人工智能·算法·语言模型·自然语言处理·大模型·推理加速
计信金边罗7 小时前
是否存在路径(FIFOBB算法)
算法·蓝桥杯·图论
MZWeiei7 小时前
KMP 算法中 next 数组的构建函数 get_next
算法·kmp
硅的褶皱7 小时前
对比分析LinkedBlockingQueue和SynchronousQueue
java·并发编程
MoFe17 小时前
【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
java·前端·.netcore