DEV Community

Cover image for Pattern Search - Optimized Naïve Search
Hagar
Hagar

Posted on • Updated on

Pattern Search - Optimized Naïve Search

Assume that all characters of pattern are different, in this case we can slide the pattern by more than 1 when a mismatch occurs.
string and pattern

  • All characters of pattern are different. slide by j
  • Slide by j. search 1 pattern found
def optimized_naïve_search(string, pattern):
    n = len(string)
    m = len(pattern)
    i = 0
    while i <= (n - m):
        for j in range(m):
            if string[i + j] != pattern[j]:
                break
            j += 1
        if j == m:
            print("pattern found at index: ", i)
            i = i + m
        elif j == 0:
            i += 1
        else:
            i = i + j


string = "abeabc"
pattern = "abc"
optimized_naïve_search(string, pattern)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)