Iam_Sandeep

KMP pattern search algorithm

Dec 9th, 2021 (edited)
751
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.54 KB | None | 0 0
  1. https://leetcode.com/problems/implement-strstr/submissions/
  2. '''
  3. LPS stands for longest proper prefix suffix.
  4. Proper prefix means prefix which is not same as original string.
  5. Same for proper suffix.
  6. '''
  7. class Solution:
  8.     def strStr(self, haystack: str, needle: str) -> int:
  9.         if needle=="":return 0
  10.         m,l,r,n=len(needle),0,1,len(haystack)
  11.         lps=[0]*m#left prefix sum
  12.         """
  13.        l,r:two pointers
  14.        """
  15.         while r<m:#creating lps of needle
  16.             if needle[l]==needle[r]:
  17.                 lps[r]=l+1
  18.                 l,r=l+1,r+1
  19.             else: #if vals are not same
  20.                 if l==0:#base case to get rid of left moving index and inc r pointer
  21.                     lps[r]=0
  22.                     r+=1
  23.                 else:
  24.                     l=lps[l-1]# till l-1 we had the prefix and suffix of size lps[l-1]. So start again search from lps[l-1].
  25.                    
  26.         """
  27.        np:needle pointer
  28.        hp:haystack pointer
  29.        """
  30.         np,hp=0,0
  31.         while hp<n:
  32.             if needle[np]==haystack[hp]:
  33.                 np,hp=np+1,hp+1
  34.             else:
  35.                 if np==0:#if we cant move np left move rp up
  36.                     hp+=1
  37.                 else:
  38.                     np=lps[np-1]#same logic of lps used above
  39.                    
  40.             if np==m:#we found the pattern or search
  41.                 return hp-m #index of start of target
  42.        
  43.         return -1 #we couldnt find any target
  44.        
  45.            
  46.        
  47.        
  48.    
  49.        
Add Comment
Please, Sign In to add comment