字符串匹配算法BF、KMP、BM的python实现。


#
BF算法 def BF(str1,str2): halen = len(str1) nelen = len(str2) j = 0 for i in range(halen): if j == nelen: break if str1[i] == str2[j]: j = j+1 else: i -= j j = 0 if j == nelen: renum = i - nelen else: renum = -1 return renum #KMP算法 def getNextList(s): n =len(s) nextList = [0,0] j = 0 for i in range(1,n): while j >0 and s[i] != s[j]: j = nextList[j] if s[i] == s[j]: j += 1 nextList.append(j) return nextList def KMP(str1,str2): n = len(str1) m = len(str2) nextList = getNextList(str2) indies = [] j = 0 for i in range(n): while str1[i] != str2[j] and j>0: j =nextList[j] if str1[i] == str2[j]: j += 1 if j == m: indies.append(i-m+1) j = nextList[j] return indies #BM算法 def getBMBC(s): BMBC = dict() for i in range(len(s)-1): char = s[i] BMBC[char] = i+1 return BMBC def getBMGS(s): BMGS = dict() BMGS[''] = 0 for i in range(len(s)): GS = s[len(s)-i-1] for j in range(len(s)-i-1): NGS = s[j:j+i+1] if GS == NGS: BMGS[GS] = len(s)-i-j-1 return BMGS def BM(str1,str2): n = len(str1) m = len(str2) i = 0 j = m indies = [] BMBC = getBMBC(str2) BMGS = getBMGS(str2) while i < n: while j > 0: if i + j - 1 >=n: return indies a = str1[i+j-1:i+m] b = str2[j-1:] if a == b: j = j-1 else: i = i + max(BMGS.setdefault(b[1:],m),j-BMBC.setdefault(str1[i+j-1],0)) j = m if j == 0: indies.append(i) i+=1 j = len(str2)

参考资料:字符串匹配的KMP算法 - 阮一峰的网络日志 (ruanyifeng.com)字符串匹配的Boyer-Moore算法 - 阮一峰的网络日志 (ruanyifeng.com)algorithm-base/BF算法.md at main · chefyuan/algorithm-base · GitHub字符串匹配BF算法、KMP算法以及BM算法Python实现_BetterManPeter的博客-CSDN博客

      

posted @ 2021-04-23 16:39  墨子32  阅读(354)  评论(0)    收藏  举报