28. 实现 strStr(KMP算法,公共子串的位置)

package com.heu.wsq.leetcode.kmp;

> 参考链接:https://www.zhihu.com/question/21923021

/**
 * 28. 实现 strStr()
 * @author wsq
 * @date 2021/4/20
 * 实现 strStr() 函数。
 * 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回  -1 。
 * 说明:
 * 当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
 * 对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
 *  
 *
 * 示例 1:
 * 输入:haystack = "hello", needle = "ll"
 * 输出:2
 * 
 * 链接:https://leetcode-cn.com/problems/implement-strstr
 */
public class StrStr {
    public int strStr(String haystack, String needle){
        int m = haystack.length();
        int n = needle.length();
        if (n == 0){
            return 0;
        }
        if (m == 0 || m < n){
            return -1;
        }
        // 采用kmp查询子串位置
        int index = kmp(haystack.toCharArray(), needle.toCharArray());
        return index;
    }

    public int kmp(char[] sOrder, char[] tOrder){
        // 获取j位置不匹配的时候,j应该回到那个位置
        int[] next = getNext(tOrder);
        int i = 0;
        int j = 0;
        while(i < sOrder.length){
            if(j >= tOrder.length){
                break;
            }
            if(j == -1 || sOrder[i] == tOrder[j]){
                i++;
                j++;
            }else{
                // kmp的核心就是这里,暴力求解可能是将j设置为0,
                // 同时i从这次开端+1的位置开始匹配,比如这次是从i=0开始展开匹配的,下次就是要从i = 1开始展开匹配
                j = next[j];
            }
        }
        if(j == tOrder.length){
            return i - j;
        }else{
            return -1;
        }
    }

    /**
     * 这里采用将公共前后缀的强度整体向后移
     * 比如:aabbab
     * 公共前后缀PMT数组为: [0, 1, 0, 0, 1, 0]
     * 变为next数组为:[-1, 0, 1, 0, 0, 1]
     * 即当索引5的地方无法匹配
     * 1. 查阅PMT数组得到索引4之前(aabba)的公共前后缀PMT[4] = 1
     * 2. 查阅next数组得到索引4之前(aabba)的公共前后缀next[5] = 1
     * 更加方便
     * @param tOrder
     * @return
     */
    private int[] getNext(char[] tOrder) {
        int n = tOrder.length;
        int[] next = new int[n];
        next[0] = -1;
        // 设置i,j位置,i用于匹配后缀,j用于匹配前缀
        int i = 0;
        int j = -1;

        while(i < n - 1){
            if(j == -1 || tOrder[i] == tOrder[j]){
                i++;
                j++;
                // 将i之前存在的公共前后串保存早next[i+1]
                next[i] = j;
            }else{
                // 如果j这个位置不匹配,那就直接将j设置为next[j],也就是j之前存在的公共前后缀长度的位置
                j = next[j];
            }
        }
        return next;
    }

    public static void main(String[] args) {
        String s = "aaababa";
        String p = "bab";
        StrStr strStr = new StrStr();
        int index = strStr.strStr(s, p);
        System.out.println(index);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值