我第二次使用Knuth-Morris-Pratt算法。顺便说一句,您的问题(和KMP解决方案)正是Python
Cookbook 2nd
Edition中的配方5.13
。您可以在http://pre.activestate.com/recipes/117214/中找到相关代码。
它找到给定序列中的 所有 正确子序列,并应将其用作迭代器:
>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s3>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s(nothing)



