LyWang

KMP-algorithm

Nov 17th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. class Solution:
  2.     """
  3.    @param source:
  4.    @param target:
  5.    @return: return the index
  6.    """
  7.     def strStr(self, source, target):
  8.         # Write your code here
  9.         if len(target)==0:
  10.             return 0
  11.         if len(source) < len(target):
  12.             return -1
  13.         lps_target = self.preprocess(target)
  14.         index_source = 0
  15.         index_target = 0
  16.         while True:
  17.             if index_target == len(target):
  18.                 return index_source - len(target)
  19.             if index_source == len(source):
  20.                 return -1
  21.             if target[index_target]==source[index_source]:
  22.                 index_source+=1
  23.                 index_target+=1
  24.             else:
  25.                 if index_target!=0:
  26.                     index_target = lps_target[index_target+1]
  27.                 else:
  28.                     index_source+=1
  29.  
  30.     def preprocess(self, target):
  31.         i=1 # this tracks the length of substring we are going to discover
  32.         length=0 #this tracks the length of lps
  33.         lps=[0] * len(target)
  34.         while i<len(target):
  35.             if target[length-1] == target[i]:
  36.                 lps[i]=length+1
  37.                 print(length)
  38.                 length += 1
  39.                 i+=1
  40.             else:
  41.                 if length == 0:
  42.                     lps[i]=0
  43.                     i+=1
  44.                 else:
  45.                     length = lps[length-1]
  46.         return lps
Add Comment
Please, Sign In to add comment