- Operating System: Windows 11
- Programming Language: Java
- IDE: IntelliJ IDEA Ultimate
-
Copy the KMP code and paste it into your preferred IDE.
-
Run the program.
-
If you want to test with other strings, go to the
mainmethod and change or add new test cases.
This program implements the KMP (Knuth-Morris-Pratt) algorithm described in Figure 3.20 of the book Compilers: Principles, Techniques, & Tools.
The algorithm is used to check if a pattern (keyword) exists inside a text.
The algorithm has two main parts:
-
Failure Function
- It is built from the pattern.
- It helps the algorithm know how much to "jump" when a mismatch happens.
-
Search Process
- The text is scanned from left to right.
- If characters match, the algorithm continues.
- If a mismatch occurs, it uses the failure function instead of starting over.
This makes the algorithm efficient.
The failure function is an array built from the pattern before starting the search.
For each position, it stores the length of the longest prefix that is also a suffix up to that point.
Its purpose is to avoid unnecessary comparisons. When a mismatch happens, instead of restarting, the algorithm uses this function to continue from a better position.
Pattern used: ababaa
- Text:
abababaab→ Result: true - Text:
abababbaa→ Result: false