Iam_Sandeep

Rabin Karp ALgorithm Pattern Search

Jun 20th, 2022 (edited)
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. #User function Template for python3
  2. '''
  3. Gives 0 to 26
  4. '''
  5. def get(x):
  6.     return ord(x)-ord('a')
  7. '''
  8. Compute hash value for given string with base 26.
  9. '''
  10. def hash(x):
  11.     ans=0
  12.     for i in x:
  13.         ans=(ans*26+get(i))%mod
  14.     return ans
  15. '''
  16. mod:largest prime number known
  17. tar:target hash value
  18. fp:first power=26**(n-1) . This can be used just to avoid writing firts power many times.
  19. patt:pattern to search
  20. s:Given string
  21. First calculate hash value of whole pattern ans store it in tar.
  22. Next now caluculate has value for first len(patt)-1 chars.
  23. Then find rolling has from n-1 to len(s).
  24. '''
  25. class Solution:
  26.     def search(self, s, patt):
  27.         mod,ans=10**9+7,ans
  28.         tar=hash(s)
  29.         n=len(s)
  30.         temp=hash(patt[:n-1])
  31.         fp=26**(n-1)
  32.        
  33.         for i in range(n-1,len(patt)):
  34.             temp=(temp*26+get(patt[i]))%mod
  35.             if temp==tar and patt[i+1-n:i+1]==s:
  36.                 ans.append(i+1-n)#(i+1-n) because you can take an example patt="san" and s="sandeep" so to add 0 to ans you have to do i+1-n
  37.             temp=(temp-fp*get(patt[i+1-n]))%mod
  38.            
  39.         return ans
  40.            
Add Comment
Please, Sign In to add comment