hash算法的应用

一、单词模式匹配

描述:单词模式字符串为“一二二一”,目标字符串为"苹果 香蕉 香蕉 苹果"则匹配成功

a=[1,2,2,1,1,3]
b=['x','y','y','x','x','z']
def word_pattern(a,b):
    #如果a,b长度不一致则直接返回False
    if len(a)!=len(b):
        return False
    #用来存储映射关系
    #例如{1:'x',2:'y',3:'z'}
    hash={}
    #用来存储是否被使用
    #如果a=[1,1,2],b=['x','y','z']
    #那么1:'y'就重复使用了,就返回False
    used={}
    for i in range(len(a)):
        if a[i] in hash:
            #不是第一次出现,检查映射关系是否匹配
            if hash[a[i]]!=b[i]:
                return False
        else:
            #检查这个单词是否使用过,使用过则返回False
            if b[i] in used:
                return False
        hash[a[i]]=b[i]
        used[b[i]]=True
    return True
print(word_pattern(a,b))

猜你喜欢

转载自www.cnblogs.com/xiximayou/p/11625113.html