给定一个单词列表,为每个单词找到最短的唯一前缀

2024-09-26 04:59:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在练习一些编码问题,我想知道是否有更好的方法来解决这个问题

给定单词列表,为每个单词找到最短的唯一前缀。你可以假设一个单词不是另一个单词的子字符串(即播放和播放不在同一单词列表中)

范例

Input: ['joma', 'john', 'jack', 'techlead']
Output: ['jom', 'joh', 'ja', 't']

以下是一些起始代码:

def shortest_unique_prefix(words):
  # Fill this in.

print(shortest_unique_prefix(['joma', 'john', 'jack', 'techlead']))
# ['jom', 'joh', 'ja', 't']

这是我的密码:

def shortest_unique_prefix(words):
  # Fill this in.
  i=0
  k=0
  j=i+1
  temp=''
  while i<len(words):
    if words[i][k] == words[j][k]:
        if k == len(words[i])-1 or k == len(words[j])-1:

            words[i]=words[i][:k+1]
            i +=1
            continue

        k +=1
    else:
            if len(words[i][:k+1])>len(temp):
                temp = words[i][:k+1]
            #words[i]=words[i][:k+1]
            k=0
            j +=1
            j=j%len(words)
            if j==i:
                words[i]=temp
                temp=''
                i +=1

                if i == len(words):
                    break
                j =(i+1)%len(words)


  return words              
                


print(shortest_unique_prefix(['joma', 'john','jack','techlead']))
# ['jom', 'joh', 'ja', 't']

我得到了正确的输出,但我想知道是否可以用更简单或更好的方法解决这个问题


Tags: prefixlenifjohn单词tempuniquewords