【LeetCode-简单题 KMP匹配算法】28. 找出字符串中第一个匹配项的下标

题目

在这里插入图片描述

方法一:常规做法 一次一次截取再做比较

在这里插入图片描述

class Solution {
    public int strStr(String haystack, String needle) {
        int haylen = haystack.length();
        int neelen = needle.length();
        if(haylen < neelen) return -1;
        for(int i = 0; i <haylen-neelen+1;i++){
            if(needle.equals(haystack.substring(i,i+neelen))) return i;
        }
        return -1;
    }
}

方法二:KMP匹配算法

主要分为两步

  1. 第一步:根据匹配串构建next前缀数组(不减-1的版本)
    在这里插入图片描述
    在这里插入图片描述

  2. 第二步:根据构建好的next数组,去文本串里面进行匹配
    在这里插入图片描述

在这里插入图片描述

class Solution {
    public int strStr(String haystack, String needle) {
        int[] next  = getNext(needle);
        int j = 0;//前缀匹配过程
        for(int i = 0 ;i<haystack.length();i++){
            //注意这里是while  不是if  while是需要一直找下去  直到找到相同前缀
            while(j>0&&haystack.charAt(i) != needle.charAt(j))  j = next[j-1];
            if(haystack.charAt(i) == needle.charAt(j)) j++;
            if(j == next.length) return i - next.length +1;
        }
        return -1;
    }
    //构造next前缀表数组
    public int[] getNext(String s){
        int[] next = new int[s.length()];
        int j = 0;
        next[0] = j;//初始化 0 号位置的相同前后缀  肯定就是0 
        for(int i = 1 ;  i<s.length() ; i++){
             //注意这里是while  不是if  while是需要一直找下去  直到找到相同前缀
            while(j>0 &&s.charAt(i) != s.charAt(j)){
                    j = next[j-1];//一直找下去  直到找到相同前后缀  否则就是直接归0
            }
            if(s.charAt(i) == s.charAt(j)){//若相等 前缀末尾j++  然后再赋给前缀末尾i位置的next数组
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值