Java Program to Implement the String Search Algorithm for Short Text Sizes
Pattern searching is a crucial problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.
A typical problem statement would be-
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat, char txt) that prints all occurrences of pat in txt.
Input: txt = "THIS IS A TEST TEXT" pat = "TExT" Output: Pattern found at index 15 Input: txt = "AABAACAADAABAABA" pat = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12
In this program, a text and a pattern are given as an input and a pattern is searched in the text, and we get all the instances of the pattern as an output.
- Take text and pattern as input.
- Run an outer for loop from 0 to length of text-length of the pattern.
- Run an inner loop from 0 to the length of the pattern.
- Through this,, for each character at each index in the text starting from that index till index+length of pattern, the pattern is searched in the text.
- If the pattern is found, print the index of the outer loop at which that pattern is found in the text.
- Else if the pattern is not found, then print it is not found.
Below is the implementation of the above approach:
Pattern Found at Position: 0 Pattern Found at Position: 8 Pattern Found at Position: 38 Total Instances Found = 3
Worst-case Time Complexity: O(m(n-m+1))
KMP algorithm is an effective way to search for a pattern inside text. While traversal when a mismatch is detected, some characters in the text of the next window are already known. Taking this advantage time complexity gets reduce to O(n).
Below is the implementation of the effective approach:
Found pattern at index 0 Found pattern at index 8 Found pattern at index 38
Time Complexity: O(n)