Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #User function Template for python3
- '''
- Gives 0 to 26
- '''
- def get(x):
- return ord(x)-ord('a')
- '''
- Compute hash value for given string with base 26.
- '''
- def hash(x):
- ans=0
- for i in x:
- ans=(ans*26+get(i))%mod
- return ans
- '''
- mod:largest prime number known
- tar:target hash value
- fp:first power=26**(n-1) . This can be used just to avoid writing firts power many times.
- patt:pattern to search
- s:Given string
- First calculate hash value of whole pattern ans store it in tar.
- Next now caluculate has value for first len(patt)-1 chars.
- Then find rolling has from n-1 to len(s).
- '''
- class Solution:
- def search(self, s, patt):
- mod,ans=10**9+7,ans
- tar=hash(s)
- n=len(s)
- temp=hash(patt[:n-1])
- fp=26**(n-1)
- for i in range(n-1,len(patt)):
- temp=(temp*26+get(patt[i]))%mod
- if temp==tar and patt[i+1-n:i+1]==s:
- 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
- temp=(temp-fp*get(patt[i+1-n]))%mod
- return ans
Add Comment
Please, Sign In to add comment