b_mt_最小唯一前缀(模拟 / 字典树)

给定一组个字符串,为每个字符串找出能够唯一识别该字符串的最小前缀。

输入
meituanapp
meituanwaimai
dianpingliren
dianpingjiehun
mt
输出
meituana
meituanw
dianpingl
dianpingj
mt

思路:只要前缀pre能在其它字符串中找到就一直变长,直到不能在其它字符串中找到前缀pre

def get(s: str,A, j, n):
    pre=''
    for i in range(n):
        while i!=j and (pre=='' or (len(pre) < len(s) and A[i].find(pre) == 0)):
            pre=s[0:len(pre)+1]
    return pre
n,A=int(input()),[]
for i in range(n):
    A.append(input())
for i in range(n):
    print(get(A[i], A, i, n))

判断前缀pre是不是别的字符串的前缀可以用字典树优化

posted @ 2021-02-19 21:10  童年の波鞋  阅读(128)  评论(0编辑  收藏  举报