KMP java实现 【算法】

6 篇文章 0 订阅
package com.using.test;

import org.junit.Test;

public class KMPTest {

    @Test
    public  void test() {
        //Arrays.stream(getNext("ababab")).forEach(System.out::println);
        String target = "ABABCABCACBAB";
        String target1 = "abbababaaababaa";
        String[] child = {"ABCAC", "ABABAB", "ABABABB"};
        String[] child1 = {"ababaaababaa"};
        for (String t : child) {
            System.out.println(target + " - " + t + ":" + compareKMP(target, t, getNext(t)));
        }
    }

    /**
     * 测试用例:
     * 主串:    ABABCABCACBAB
     * 模式串:ABCAC 5
     * 模式串:ABABAB -1
     * 模式串:ABABABB -1
     * 主串:    abbababaaababaa
     * 模式串:ababaaababaa 3
     * */
    private static int compareKMP(String str1, String str2, int[] next){
        int i = 0;
        int j = 0;
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        while (i < chars1.length && j < chars2.length){
            if (chars1[i] == chars2[j]){
                i ++;
                j ++;
            }else if (j>0){
                j = next[j];
            }else{
                i ++;
            }
        }
        return j == chars2.length ? i-j : -1;
    }

    private static int[] getNext(String str){
        char[] chars = str.toCharArray();
        if (chars.length == 1){
            return new int[]{-1};
        }
        int[] next = new int[chars.length];
        next[0] = -1;
        next[1] = 0;
        int cn = 0;
        int i = 2;
        while(i < chars.length){
            if (chars[cn] == chars[i-1]){
                next[i++] = ++cn;
            }else if(cn > 0){
                cn = next[cn];
            }else{
                next[i++] = 0;
            }
        }
        return next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值