1 #!/usr/bin/env python 2 #-*- coding: utf-8 -*- 3 import sys 4 5 reload(sys) 6 sys.setdefaultencoding(‘utf-8‘) 7 8 9 class PatternMatching(object): 10 11 def brute_force(self, str_s, str_t): 12 """BF算法 13 """ 14 base = 0 15 len_s = len(str_s) 16 len_t = len(str_t) 17 18 while base + len_t <= len_s: 19 step = 0 20 while step < len_t: 21 if str_t[step] == str_s[base + step]: 22 step += 1 23 continue 24 base += 1 25 break 26 if step == len_t: 27 return base 28 return -1 29 30 31 if __name__ == ‘__main__‘: 32 str_s = "ababcabcaabab" 33 str_t = "ababd" 34 calc = PatternMatching() 35 print calc.brute_force(str_s, str_t)
原文:https://www.cnblogs.com/zhongmiaozhimen/p/11239000.html