[Java][Leetcode simple] 28. 找出字符串中第一个匹配项的下标

暴力匹配

I 如果大于m - n则永远不可能有匹配成功的字符串(长度太短,不够匹配)

java 复制代码
class Solution {
   public  int strStr(String haystack, String needle) {
        int m = haystack.length();
        int n = needle.length();
        int cnt = 0;
        int tmp = 0;

        if( m < n) return -1;
    
        for(int i = 0 ;i<= m - n;i++){
            tmp = i;
            cnt = 0;

            while(cnt < n){
                if(haystack.charAt(tmp) == needle.charAt(cnt)){
                    tmp++;
                    cnt++;
                }else{
                    break;
                }
            }
            if(cnt == n){
                return i;
            }
        }

        return -1;

    }
}

KMP算法

和暴力匹配相比,暴力法一旦匹配失败,文本指针要回退、模式串也要从头开始,会做很多重复比较,效率不高。

而 KMP 最大的特点就是:文本指针永远不回退,只往前走。

它的核心思想是:利用模式串本身的前后缀重复信息,提前预处理出一个 next 数组,记录每个位置匹配失败后,模式串应该跳到哪里继续比较,而不是直接回到 0。

这样就避免了重复比较,把时间复杂度从暴力的 O (n*m) 优化到了 O(n + m),非常稳定高效。

java 复制代码
class Solution {
   public  int strStr(String haystack, String needle) {
        int m = haystack.length();
        int n = needle.length();
       
        
        if( n == 0) return 0;
        if( m < n) return -1;
    
        int[] next = new int[n];

        for(int i =1,j=0;i<n; i++){
             while(j > 0 && needle.charAt(i) != needle.charAt(j)){
                j = next[j-1];
             }

             if(needle.charAt(i) == needle.charAt(j)){
                j++;
             }
             next[i] = j;
        }

        for( int i=0,j=0;i<m;i++){
            while(j>0 && haystack.charAt(i) != needle.charAt(j)){
                j = next[j-1];
            }

            if(haystack.charAt(i) == needle.charAt(j)){
                j++;
            }
            if(j==n){
                return  i - n +1;
            }
        }
        return -1;

    }
}
相关推荐
QQ_21696290963 小时前
【源码编号:project93375】SpringBoot汽车维修管理信息系统:客户车辆、维修预约、工单派发、配件结算全流程实战
java·spring boot·后端·汽车·springboot·需求分析
jimy14 小时前
c++隐式移动构造、强制拷贝省略、返回具名局部变量
开发语言·c++
xcl09254 小时前
流浪宠物领养管理系统开发实战:从需求分析到落地的完整指南
java·spring boot·需求分析·宠物
v_for_van4 小时前
C语言__attribute__
服务器·c语言·开发语言·mcu·嵌入式·嵌入式实时数据库
lhldsg4 小时前
家校托管互通系统技术架构与实战设计
java·经验分享·小程序·架构
工业一体机老司机4 小时前
Python实现工业一体机Modbus-TCP通信-从协议解析到多设备轮询实战
开发语言·python·tcp/ip
GIS数据转换器4 小时前
智慧林草“一张图“平台
java·大数据·服务器·前端·javascript·数据库·人工智能
fpcc4 小时前
跟我学C++中级篇—static_assert和assert
开发语言·c++
2401_885885044 小时前
国际语音php接口代码示例:PHP使用cURL快速调用语音发送API
android·开发语言·前端·人工智能·python·php·语音识别
gis开发之家4 小时前
Spring Boot 4 深度解析,JdbcTemplate 实战——轻量级数据库操作方案
java·数据库·spring boot·后端