KMP算法

本文提供了一个使用KMP算法进行字符串匹配的Java实现示例。该示例通过定义`Main`类并重写`main`方法来展示如何利用KMP算法搜索目标模式串在源串中的位置。此外,还提供了用于计算模式串部分匹配表的方法。

public class Main {

    public static void main(String[] args) {
        char s[] = "ababca12341234fgdf".toCharArray();
        char t[] = "3412".toCharArray();
        int x = search(s, t);
        System.out.println(x);
    }

    private static int[] next(char[] pattern) {
        int[] result = new int[pattern.length];
        result[0] = -1;
        result[1] = 0;

        int i = 2;
        while (i < pattern.length) {
            if ((pattern[i - 1] == pattern[result[i - 1]])) {
                result[i] = result[i - 1] + 1;
            } else {
                result[i] = 0;
            }
            i++;
        }
        return result;
    }

    private static int search(char[] s, char[] t) {
        int i = 0, j = 0;
        int[] next = next(t);

        while (i < s.length) {
            if (s[i] == t[j]) {
                i++;
                j++;
                if (j == t.length) {
                    return i - j;
                }
            } else {
                j = next[j];
                if (j == -1) {
                    j++;
                    i++;
                }
            }
        }
        return -1;
    }
}

转载于:https://www.cnblogs.com/sunliho/archive/2010/07/04/1770738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值