Advertisement
Iam_Sandeep

Horspool Boyer Moore ALgorithm Pattern Matching

Jun 20th, 2022
887
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. class Solution:
  2.     def strStr(self, text: str, pat: str) -> int:
  3.         if not pat:
  4.             return 0
  5.         m,n=len(text),len(pat)
  6.         pre=[n]*256 #preprocessing work
  7.         if n>m:return -1
  8.  
  9.         for i in range(n-1):#vvvv Imp .Here preprocessing need to be done till n-1 th index . If already that pat[n-1] exists already in pat at some other index then it takes its index else it will be length
  10.             pre[ord(pat[i])]=n-i-1
  11.        
  12.         shift=n-1#shift is pointer to point text . It is constant for each iteration
  13.    
  14.         while shift<m:
  15.             j=n-1
  16.             i=shift #i,j are used for traversing so shift doesnt affect
  17.             while j>=0 and text[i]==pat[j]:
  18.                 i,j=i-1,j-1
  19.             #print((i,j))
  20.             if j<0:#success
  21.                 return i+1
  22.             else:# when match does nt happen check the length to be moved by searching in pre array(preprocessing table)
  23.                 shift=shift+pre[ord(text[shift])]      
  24.         return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement