题解 | #HJ27 查找兄弟单词#
查找兄弟单词
https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
方法1
兄弟单词,不能完全一样,只允许顺序不一样。可以通过统计字母出现次数来判断。
def char_count(s): dic = {} for c in s: dic[c] = dic.get(c, 0) + 1 return dic s = input() li = s.split() n = int(li[0]) dic_words = li[1 : n + 1] x = li[n + 1] k = int(li[-1]) brother_words = [] for dic_word in dic_words: if char_count(dic_word) == char_count(x) and dic_word != x: brother_words.append(dic_word) print(len(brother_words)) if len(brother_words): brother_words = sorted(brother_words) if k <= len(brother_words): print(brother_words[k - 1])
方法2
通过比较两个单词字符串排序后的列表是否相同来判断它们是否为“兄弟单词”
while True: try: data = input().split() n = int(data[0]) # 单词的个数 words = data[1:-2] # 字典单词列表 target = data[-2] # 目标单词 k = int(data[-1]) # 要找的兄弟单词的序号 num = 0 bros = [] for word in words: if word == target: continue elif sorted(word) == sorted(target): num += 1 bros.append(word) bros.sort() # 按字典序排序兄弟单词 print(num) # 输出兄弟单词的个数 if k <= len(bros): print(bros[k - 1]) # 输出第k个兄弟单词 except: break#华为机试#
【牛客站内】华为机试题解 文章被收录于专栏
【牛客站内】 分享个人刷题的思路和解法