题解 | 查找兄弟单词

查找兄弟单词

https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68

主要是两点

  1. 如何判断为兄弟单词:长度相等,不等于原字符串,每个目标单词的字母计数与x相等
  2. 如何排序:题干写的很清楚了,一个一个比较即可。甚至可以直接将一个字符串转化为26进制的数来处理,最长为10个字符,一个int完全足够存储了。然后排序后恢复成原单词就好了。
import sys

def get_alphabet(s):
    result = {}
    for each in s:
        if each in result:
            result[each] += 1
        else:
            result[each] = 1
    return result


for line in sys.stdin:
    a = line.split()
    k = int(a.pop(-1))
    n = int(a.pop(0))
    x = a.pop(-1)

    result_list = []
    # 记录x的字母数量
    x_alphabet_dict = get_alphabet(x)
    len_x = len(x)
    for each in a:
        # 长度要一致
        if len(each) != len_x:
            continue
        # 不能完全相同
        elif each == x:
            continue
        # 计算字母数
        else:
            curr_chr_dict = get_alphabet(each)
            for c in x_alphabet_dict:
                if x_alphabet_dict[c] != curr_chr_dict.get(c, 0):
                    break
            else:
                result_list.append(each)
    print(len(result_list))

    if k <= len(result_list):
        result_list = sorted(result_list)
        print(result_list[k-1])


    

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务