常考数据结构与算法-KMP算法

public class KMP {
    public static void main(String[] args) {
        String s1 = "xiatiannihao";
        String s2 = "a";

        System.out.println(getStringIndex(s1,s2));
    }

    public static int getStringIndex(String str1, String str2){
        if(str1 == null || str2==null || str1.length()<str2.length()){
            return 0;
        }

        char[] chs1 = str1.toCharArray();
        char[] chs2 = str2.toCharArray();
        int s1 = 0;
        int s2 = 0;

        int[] next = getNextArray(chs2);  // 求next数组
        while(s1<str1.length() && s2<str2.length()){
            if(chs1[s1] == chs2[s2]){
                s1++;
                s2++;
            }else if(next[s2] != -1){
                s2 = next[s2];
            }else{
                s1++; // 如果str1同 str2的第一个字符都不相等,那么str1就向后移一个位置比较
            }
        }

        return s2 == str2.length() ? s1-s2 : -1;
    }

    public static int[] getNextArray(char[] str2){
        if(str2.length == 1){
            return new int[]{-1};
        }

        int[] next = new int[str2.length];
        next[0] = -1; // 人为固定
        next[1] = 0; // 人为固定
        int i = 2; // 从下标2开始
        int cn = 0; // 一开始和下标0比较
        while(i<str2.length){
            if(str2[i-1] == str2[cn]){
                next[i++] = ++cn;
            }else if(cn > 0){
                cn = next[cn]; // 从已有的next数组获取信息
            }else{
                next[i++] = 0;
            }
        }
        return next;
    }
}

kmp算法很经典。影响了后续很多的算法,这些算法借鉴了kmp算法的思想。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值