search
HomeJavajavaTutorialWhat is the implementation method of KMP algorithm in Java?

Illustration

The kmp algorithm has a certain similarity with the idea of ​​the bm algorithm mentioned before. As mentioned before, there is the concept of a good suffix in the bm algorithm, and there is a concept of a good prefix in kmp. What is a good prefix? Let's first look at the following example.

What is the implementation method of KMP algorithm in Java?

Observe the above example, the already matched abcde is called a good prefix, a does not match the following bcde, so there is no need to compare again, slide directly after e That’s it.

What if there are matching characters in the good prefix?

What is the implementation method of KMP algorithm in Java?

Observe the above example, if we slide directly after the good prefix at this time, we will slide too much and miss the matching substring. So how do we perform reasonable sliding based on good prefixes?

In fact, it is to check whether the prefix and suffix of the current good prefix match, find the longest matching length, and slide directly. In view of finding the longest matching length more than once, we can initialize an array first and save the longest matching length under the current good prefix. At this time, our next array will come out.

We define a next array, which represents the length of the longest matching substring of the prefix and suffix of the good prefix under the current good prefix. This longest matching length means that this substring has been matched before, not It is necessary to match again, starting directly from the next character of the substring.

What is the implementation method of KMP algorithm in Java?

Do we need to match every character every time we calculate next[i]? Can we deduce based on next[i - 1] to reduce unnecessary comparisons? .

With this idea, let’s take a look at the following steps:

Assume next[i - 1] = k - 1;

If modelStr[k] = modelStr[ i] then next[i]=k

What is the implementation method of KMP algorithm in Java?

##If modelStr[k] != modelStr[i], can we directly determine next[i] = next[i - 1]?

What is the implementation method of KMP algorithm in Java?

Through the above example, we can clearly see that next[i]!=next[i-1], then modelStr[k]!=modelStr At [i], we already know next[0], next[1]...next[i-1], how to overturn next[i]?

Assume that modelStr[x…i] is the longest suffix substring that the prefix and suffix can match, then the longest matching prefix substring is modelStr[0…i-x]

What is the implementation method of KMP algorithm in Java?

When we find the longest matching string, its previous second-longest matching string (excluding the current i), that is, modelStr[x…i-1] should have been solved before. , so we only need to find this certain matching string that has been solved. Assume that the prefix substring is modelStr[0…i-x-1], the suffix substring is modelStr[x…i-1], and modelStr[i-x] == modelStr [i], this prefix and suffix substring is the secondary prefix substring, plus the current character is the longest matching prefix and suffix substring.

Code implementation

First of all, the most important next array in the kmp algorithm. This array marks the number of longest prefix and suffix matching substring characters up to the current subscript. In the kmp algorithm, if If a certain prefix is ​​a good prefix, that is, it matches the pattern string prefix, we can use certain techniques to slide more than one character forward. See the previous explanation for details. We don't know in advance which are good prefixes, and the matching process is more than once, so we call an initialization method at the beginning to initialize the next array.

1. If the next character of the longest prefix substring of the previous character == the current character, the longest prefix substring of the previous character can be directly added to the current character

2 .If not equal, you need to find the next character of the previously existing longest prefix substring that is equal to the current substring, and then set the longest prefix suffix substring of the current character substring

int[] next ;
    /**
     * 初始化next数组
     * @param modelStr
     */
    public void init(char[] modelStr) {
        //首先计算next数组
        //遍历modelStr,遍历到的字符与之前字符组成一个串
        next = new int[modelStr.length];
        int start = 0;
        while (start < modelStr.length) {
            next[start] = this.recursion(start, modelStr);
            ++ start;
        }
    }

    /**
     *
     * @param i 当前遍历到的字符
     * @return
     */
    private int recursion(int i, char[] modelStr) {
        //next记录的是个数,不是下标
        if (0 == i) {
            return 0;
        }
        int last = next[i -1];
        //没有匹配的,直接判断第一个是否匹配
        if (0 == last) {
            if (modelStr[last] == modelStr[i]) {
                return 1;
            }
            return 0;
        }
        //如果last不为0,有值,可以作为最长匹配的前缀
        if (modelStr[last] == modelStr[i]) {
            return next[i - 1] + 1;
        }
        //当next[i-1]对应的子串的下一个值与modelStr不匹配时,需要找到当前要找的最长匹配子串的次长子串
        //依据就是次长子串对应的子串的下一个字符==modelStr[i];
        int tempIndex = i;
        while (tempIndex > 0) {
            last = next[tempIndex - 1];
            //找到第一个下一个字符是当前字符的匹配子串
            if (modelStr[last] == modelStr[i]) {
                return last + 1;
            }
            -- tempIndex;
        }
        return 0;
    }

and then start using the next array Match, start matching from the first character, and find the first unmatched character. At this time, all the previous ones are matched. Next, first judge whether it is a complete match. If it is a direct return, if not, judge whether the first character is matched. If one does not match, it will match directly to the next one. If there is a good prefix, the next array is used at this time. Through the next array, we know where the current matching can start, and there is no need to match the previous ones.

public int kmp(char[] mainStr, char[] modelStr) {
        //开始进行匹配
        int i = 0, j = 0;
        while (i + modelStr.length <= mainStr.length) {
            while (j < modelStr.length) {
                //找到第一个不匹配的位置
                if (modelStr[j] != mainStr[i]) {
                    break;
                }
                ++ i;
                ++ j;
            }
            if (j == modelStr.length) {
                //证明完全匹配
                return i - j;
            }
            //走到这里找到的是第一个不匹配的位置
            if (j == 0) {
                ++ i;
                continue;
            }
            //从好前缀后一个匹配
            j = next[j - 1];
        }
        return -1;
    }

The above is the detailed content of What is the implementation method of KMP algorithm in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How can I use Java's RMI (Remote Method Invocation) for distributed computing?How can I use Java's RMI (Remote Method Invocation) for distributed computing?Mar 11, 2025 pm 05:53 PM

This article explains Java's Remote Method Invocation (RMI) for building distributed applications. It details interface definition, implementation, registry setup, and client-side invocation, addressing challenges like network issues and security.

How do I use Java's sockets API for network communication?How do I use Java's sockets API for network communication?Mar 11, 2025 pm 05:53 PM

This article details Java's socket API for network communication, covering client-server setup, data handling, and crucial considerations like resource management, error handling, and security. It also explores performance optimization techniques, i

How can I create custom networking protocols in Java?How can I create custom networking protocols in Java?Mar 11, 2025 pm 05:52 PM

This article details creating custom Java networking protocols. It covers protocol definition (data structure, framing, error handling, versioning), implementation (using sockets), data serialization, and best practices (efficiency, security, mainta

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.