005_013 Pythonはサブシーケンス文字列を探してfindを使うべきで、さもなくばKMPを使うべきです

807 ワード

コードは次のとおりです.
#encoding=utf-8

print '  '

#     

#      find    KMP
def KnuthMorrisPratt(text, pattern):    
    pattern = list(pattern)
    length = len(pattern)
   
    shifts = [1] * (length + 1)
    shift = 1
    for pos, pat in enumerate(pattern):
        while shift <= pos and pat != pattern[pos-shift]:
            shift += shifts[pos-shift]
        shifts[pos+1] = shift
    
    startPos = 0
    matchLen = 0
    for c in text:
        while matchLen == length or matchLen >= 0 and pattern[matchLen] != c:
            startPos += shifts[matchLen]
            matchLen -= shifts[matchLen]
        matchLen += 1
        if matchLen == length: yield startPos


for i in KnuthMorrisPratt([1,2,3,4,2,3],[2,3]):
    print i

印刷結果は次のとおりです.
中国1 4