Naive string matching algorithm

The naive string matching algorithm, also known as the brute-force algorithm, is a simple pattern matching algorithm used to find occurrences of a pattern within a text. Here's the pseudocode for the naive string matching algorithm:

NaiveStringMatch(pattern, text):
n = length(text)
m = length(pattern)
occurrences = []

for i = 0 to n - m do
    j = 0
    while j < m and text[i + j] = pattern[j] do
        j = j + 1

    if j = m then
        occurrences.append(i)

return occurrences

Let's go through the pseudocode step by step:

1. `n` represents the length of the text, and `m` represents the length of the pattern.

2. Initialize an empty list `occurrences` to store the starting indices of pattern occurrences.

3. Iterate `i` from 0 to `n - m` (inclusive) to slide the pattern window over the text.

4. Inside the loop, set `j` to 0 to represent the current character index in the pattern.

5. While `j` is less than `m` (the length of the pattern) and the characters at `text[i + j]` and `pattern[j]` are equal, continue the loop.

6. If `j` reaches `m` (indicating a complete match), add `i` to the `occurrences` list.

7. Finally, return the `occurrences` list containing the starting indices of pattern matches.


Please note that the pseudocode assumes 0-based indexing for arrays and lists. Also, keep in mind that the naive string matching algorithm has a time complexity of O((n - m + 1) * m), where n is the length of the text and m is the length of the pattern.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext