用Python简单写一个KMP

KMP

简单写一个KMP算法:


def Transform_Table(pattern):
    state = len(pattern)
    table = [[0 for _ in range(256)] for _ in range(state)]

    X = 0
    table[0][ord(pattern[0])] = 1

    for i in range(1, len(pattern)):
        current_char = ord(pattern[i])
        for j in range(256):
            if j == current_char:
                table[i][j] = i + 1
            else:
                table[i][j] = table[X][j]

        X = table[X][current_char]
    
    return table

def search(str_data,table):
    final_state = len(table)

    result = []
    state = 0
    for i in range(len(str_data)):
        state = table[state][ord(str_data[i])]
        if state == final_state:
            result.append(i - final_state + 1)
            state = 0
    
    return result

pattern = "ababc"
table = Transform_Table(pattern)

str_data = "ababababc"

print(search(str_data,table))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值