DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Pattern Search - Optimized NaΓ―ve Search
Hagar
Hagar

Posted 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)

12 APIs That You Will Love

>> Check out this classic DEV post <<