实现 strStr()

2022-07-28

LeetCode刷题记14

28. 实现 strStr()

题目

可以暴力也可以KMP,下面放KMP

class Solution {
    public static int[] getNext(String str) {
        char[] chs = str.toCharArray();
        int[] next = new int[chs.length];
        next[0] = -1;
        int j = 0;
        int k = -1;
        while (j < chs.length - 1) {
            if (k == -1 || chs[j] == chs[k]) {
                next[++j] = ++k;
            } else {
                k = next[k];
            }
        }
        return next;
    }
    public static int KMP(String ts, String ps) {
        char[] t = ts.toCharArray();
        char[] p = ps.toCharArray();
        int i = 0; // 主串的位置
        int j = 0; // 模式串的位置
        int[] next = getNext(ps);
        while (i < t.length && j < p.length) {
            if (j == -1 || t[i] == p[j]) { // 当j为-1时,要移动的是i,当然j也要归0
                i++;
                j++;
            } else {
                j = next[j]; // j回到指定位置
            }
        }
        if (j == p.length) {
            return i - j;
        } else {
            return -1;
        }
    }

    public int strStr(String haystack, String needle) {
        if (needle.equals("")) {
            //不能needle == ""
            return 0;
        } else if (haystack.length() == 0) {
            return -1;
        }
        return KMP(haystack, needle);
    }
}

KMP讲解
我自己还有点迷迷糊糊的,今天一点也看不进去了,挖个坑先。

本文地址:https://blog.csdn.net/weixin_44013557/article/details/109605189

《实现 strStr().doc》

下载本文的Word格式文档,以方便收藏与打印。