Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def strStr(self, text: str, pat: str) -> int:
- if not pat:
- return 0
- m,n=len(text),len(pat)
- pre=[n]*256 #preprocessing work
- if n>m:return -1
- 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
- pre[ord(pat[i])]=n-i-1
- shift=n-1#shift is pointer to point text . It is constant for each iteration
- while shift<m:
- j=n-1
- i=shift #i,j are used for traversing so shift doesnt affect
- while j>=0 and text[i]==pat[j]:
- i,j=i-1,j-1
- #print((i,j))
- if j<0:#success
- return i+1
- else:# when match does nt happen check the length to be moved by searching in pre array(preprocessing table)
- shift=shift+pre[ord(text[shift])]
- return -1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement