初级农民-请到新手上路获取积分
- 积分
- 5
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2023-1-6
- 最后登录
- 1970-1-1
|
本帖最后由 拧眉横目的手电筒 于 2024-3-1 23:45 编辑
the KMP table below stores the max mathching length up to each index in target. for target="xzxyxyy", table returns [0, 1, 2, 2, 3, 3, 1]. Then apply the table to S just like KMP to find mathcing pattern in S.
in "xzxyxyy", say for index 5, the 2nd "y", given that we have "xyx" match "xzx", g is now 3. then for the 2nd y, we know it should match the y in "xzxy". in "xzxy" y shows up for the first time, but in "xyx" we know y has already appeared, so the matching fails. g reduces to table[g-1] =2, we continue the KMP searching process
s="abbad"
target="xzxyxyy"
w, w2l=dict(), collections.defaultdict(lambda :[float('-inf')])
for i,j in enumerate(target):
w2l[j]+=[i]
w[i]=len(w2l[j])-1
g, table=0, [0]
for i in range(1,len(target)):
j=target[i]
while g:
k=w2l[target[g]][1]
if (k>=g and w2l[j][w[i]]-w2l[j][w[i]-1]>g) or (k<g and target[i-g+k]==j):
g+=1
break
g=table[g-1]
g+=g==0
table+=[g]
补充内容 (2024-03-02 13:22 +08:00):
s="zyzx"
target="xzxyxyy"
w,w2l=dict(), collections.defaultdict(lambda :[float('-inf')])
for i,j in enumerate(target):
w[i]=i-w2l[j][-1]
w2l[j]+=[i]
g,table=0, [0]
for i in range(1,len(target)):
j=target[i]
while g:
k=w2l[target[g]][1]
if (k>=g and w[i]>g) or (k<g and target[i-g+k]==j):
g+=1
break
g=table[g-1]
g+=g==0
table+=[g]
补充内容 (2024-03-02 13:23 +08:00):
第一次发帖 原来这论坛发了就没法修改阿
补充内容 (2024-03-02 13:27 +08:00):
我发到leetcode了 排版好一点
https://leetcode.com/discuss/int...site-or-Secret-Word |
|