题解 | #查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
aline = input().split()
n = int(aline[0])
# aset = set(aline[1:-2]) # 字典若去重,则用集合(set)
dictionary = aline[1:-2] # 字典若不去重,则用列表(list)
x = aline[-2]
k = int(aline[-1])
characters = set(x)
freq = {}
for i in characters:
freq[i] = x.count(i)
brothers = []
for ele in dictionary:
if ele != x and len(ele) == len(x):
# 不考虑单词中有重复字符
# for i in characters:
# if i not in ele:
# break
# brothers.append(ele)
# 考虑单词中有重复字符
# 方法一:x的字母频次(可存为常量字典)若与ele的字母频次不同,则非兄弟单词
for i in characters:
if freq[i] != ele.count(i):
break
else:
brothers.append(ele)
# 方法二:ele和x分别排序成新的字符串(sorted(x)可存为常量),新字符串相等即为兄弟单词;长单词排序比较耗时
# if sorted(ele) == sorted(x):
# brothers.append(ele)
brothers.sort(key=None, reverse=False)
print(len(brothers))
if k < len(brothers):
print(brothers[k - 1])
#刷题#