首页 > 试题广场 >

查找兄弟单词

[编程题]查找兄弟单词
  • 热度指数:440281 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
\hspace{15pt}定义一个字符串 s 的“兄弟单词”为:将 s 重新排序后得到的与原字符串不同的新字符串。
\hspace{15pt}现在,对于给定的 n 个字符串 s_1, s_2, \dots, s_n 和另一个单独的字符串 x,你需要解决两个问题:
\hspace{23pt}\bullet\,统计这 n 个字符串中,有多少个是 x 的“兄弟单词”(注意,这 n 个字符串可能有重复,重复字符串分别计数);
\hspace{23pt}\bullet\,将这 n 个字符串中 x 的“兄弟单词”按字典序从小到大排序,输出排序后的第 k 个兄弟单词(从 1 开始计数)。特别地,如果不存在,则不输出任何内容。

【名词解释】
\hspace{15pt}从字符串的第一个字符开始逐个比较,直至发现第一个不同的位置,比较这个位置字符的字母表顺序,字母序较小的字符串字典序也较小;如果比较到其中一个字符串的结尾时依旧全部相同,则较短的字符串字典序更小。

输入描述:
\hspace{15pt}在一行上依次输入:
\hspace{23pt}\bullet\,一个整数 n \left(1 \leqq n \leqq 10^3\right) 代表字符串的个数;
\hspace{23pt}\bullet\,n 个长度为 1 \leqq {\rm length}(s_i) \leqq 10,仅由小写字母构成的字符串 s_1, s_2, \dots, s_n
\hspace{23pt}\bullet\,一个长度为 1 \leqq {\rm length}(x) \leqq 10,仅由小写字母构成的字符串 x
\hspace{23pt}\bullet\,一个整数 k \left(1 \leqq k \leqq n\right) 代表要查找的第 k 小的兄弟单词的序号。


输出描述:
\hspace{15pt}第一行输出一个整数,代表给定的 n 个字符串中,x 的“兄弟单词”的数量;
\hspace{15pt}第二行输出一个字符串,代表将给定的 n 个字符串中 x 的“兄弟单词”按字典序排序后的第 k 小兄弟单词。特别地,如果不存在,则不输出任何内容(完全省略第二行)。
示例1

输入

3 abc bca cab abc 1

输出

2
bca

说明

\hspace{15pt}在这个样例中,x 的兄弟单词为 \texttt{\texttt{\texttt{\texttt{\texttt{ 。其中,标橙色的两个字符串存在于所给定的 n 个字符串中。第 1 小的兄弟单词为 \texttt{
示例2

输入

3 a aa aaa a 1

输出

0

说明

\hspace{15pt}在这个样例中,按照定义,字符串 \texttt{ 没有兄弟单词。

备注:
本题已于下方时间节点更新,请注意题解时效性:
1. 2025-05-30 更新题面。
2. 2024-12-29 更新题面。
line = input().split()
n = int(line[0])
s_list = line[1:n+1]
x = line[n+1]
k = int(line[-1])
brother_list = []
for ss in s_list:
if len(ss)!=len(x):
continue
if sorted(x)==sorted(ss) and ss!=x:
brother_list.append(ss)
brother_list.sort()
print(len(brother_list))
if 1<=k<=len(brother_list):
print(brother_list[k-1])
编辑于 2025-03-15 15:31:07 回复(0)
最后一组数据过不去,看不到测试数据,不知道原因啊
import sys

# def searchWords(self):
inputli = list(input().split())
n = int(inputli[0])
dic = inputli[1:n+1]
k = int(inputli[-1])
targWord = inputli[-2]
count = 0
broWord = list()
for i in range(len(dic)):
    # print(sorted(dic[i]))
    if (sorted(dic[i]) ==  sorted(targWord)) and (dic[i]!=targWord):
        count +=1
        broWord.append(dic[i])
        # if (count == k) :
        #     broWord = dic[i]
print(count)
if (count > 0) and (count > k) :
    print(broWord[k-1])

    


编辑于 2024-07-11 13:49:27 回复(0)
while True:
    try:
        # 获取信息
        a = input().split(' ')
        #print(a)
        num = a[0]
        k = int(a[-1])
        target = a[-2]
        li = a[1:-2]

        ans_list = []
        # 去掉和目标单词相同的单词
        while target in li:
            li.remove(target)
        # 用sorted和list判断字母组成是否相同
        target_list = sorted(list(target))
        for word in li:
            if sorted(list(word)) == target_list:
                ans_list.append(word)
        # 对符合要求的单词进行排序
        ans_list.sort()
        #print(ans_list)
        print(len(ans_list))
        # 题目中没有写的条件,可能会出现溢出
        if len(ans_list) != 0 and k <= len(ans_list):
            print(ans_list[int(k)-1])
    except:
        break
题目中没有写出可能会有溢出现象,不过也没有写k一定是满足要求的。
发表于 2022-07-02 14:00:42 回复(0)
什么狗东西
length,*w_list,word,k = input().split(" ")

def is_brother(w1, w2):
    if w1 != w2 and sorted(w1) == sorted(w2):
        return True
    else:
        return False

def solve(arr, word, k):
    dictionary = sorted(arr)
    find = []
    for w in dictionary:
        if is_brother(w, word):
            find.append(w)

    if (len(find) <= int(k)):
        print(len(find))
    else:
        print(len(find))
        print(sorted(list(find))[int(k)-1])
    
solve(w_list, word, k)    

发表于 2022-06-23 11:27:44 回复(0)
python loop麻烦方法:
str1 = input()
str1 = str1.split()
n = int(str1[0]) #记录n个单词
k = int(str1[-1]) #记录最终数字k
del str1[0] 
del str1[-1]# 删除数字项
check = str1[-1] #记录待查找单词
ind =[]
cc = list(check)
cc = set(cc)
cc = list(cc)
cc =''.join(cc) #去除待查找单词重复项
for i in range (len(cc)):
    ind.append(check.count(cc[i])) #记录每个字母出现次数
buffer = str1[-1] 
del str1[-1] #删除查找单词
check = list(check)
record =[]
for i in range (len(str1)):
    c=0
    for ii in range (len(cc)):#逐个与新单词对比,要同时满足长度一致,出现次数一致,及含有此字母项则计数器+1
        if cc[ii] in list(str1[i]) and len(check) == len(list(str1[i])) and str1[i] != buffer and str1[i].count(cc[ii]) == ind[ii]:
            c = c +1
    if c == len(cc): #计数器=字母总类别数代表全类别字母通过
       record.append(str1[i])
record = list(record)
print(len(record))
record = sorted(record)
if 0<= k-1 <= len(record) and record != []: #防止没有符合的情况不输出
    print(record[k-1])


发表于 2021-06-23 18:13:10 回复(0)
python3,题目描述中,注意重复单词也算作是兄弟单词,比如测试用例中的这样
473个数据的那个测试样例,结果是
6
adbcb
但是,这里的6个是:['adbcb', 'bacbd', 'badbc', 'bcbda', 'bcbda', 'cdbab'],请注意有重复单词
下面是我的代码,中间的set就不需要了。
while True:
    try:
        s=input().split(" ")
        n=int(s.pop(0))
        k=int(s.pop())
        tar=s.pop()
        #重复单词也算兄弟单词,这个题目没有太明确说明
        #s = list(set(s))
        res = []
        for item in s:
            if len(item)==len(tar) and item!=tar and sorted(item)==sorted(tar):
                res.append(item)
        res=sorted(res)
        print(len(res))
        print(res)
        if res and len(res)>k:
            print(res[k-1])
    except:
        break



发表于 2021-05-12 03:33:56 回复(0)
import sys

test_data = sys.stdin.readline().strip().split()

num = int(test_data[0])
k = int(test_data.pop())

input_str = test_data.pop()

probable_word_list = test_data[1:]

def get_str_map(string):
    target_s_dict = {}
    for s in string:
        if s not in target_s_dict:
            target_s_dict[s] = 1
        else:
            target_s_dict[s] += 1
    return target_s_dict


input_str_map = get_str_map(input_str)

result = []

for word in probable_word_list:
    word_s_map = get_str_map(word)
    if word_s_map == input_str_map and word != input_str:
        result.append(word)
    
    
result.sort()
    
print(len(result))

if k <= len(result) - 1:
    print(result[k-1])
发表于 2021-04-11 14:53:58 回复(0)
dab 和bad 不是兄弟单词?
发表于 2021-03-22 13:19:10 回复(2)
while True:
    try:
        a=input().split()
        word,x,k,m,l=a[1:-2],a[-2],int(a[-1]),0,[]
        def str_sort(s=''):
            if len(s) <= 1:
                return [s]
            str_list = []
            for i in range(len(s)):
                for j in str_sort(s[0:i] + s[i + 1:]):
                    str_list.append(s[i] + j)
            return str_list
        s = str_sort(x)
        for i in word:
            if i in s and i!=x:
                l.append(i)
                m+=1
        l=sorted(l)
        print(m)
        print(l[k-1])
    except:
        break
编辑于 2021-03-11 18:08:33 回复(0)
def is_brother(word, str):
    return (sorted(word) == sorted(str)) and (word != str)

l = input().split()
n, l, str, k = int(l[0]), l[1:-2], l[-2], int(l[-1])

brother = []
for word in l:
    if is_brother(word, str):
        brother.append(word)

brother.sort()
print(len(brother))
if k < len(brother):
    print(brother[k-1])

发表于 2021-03-03 20:08:35 回复(0)
求个大佬啊阿啊。。。为啥自测过了,最终返回非零。
代码如下
import sys
s=sys.stdin.readlines()
w=list(map(lambda x: x.strip(),s))
w1=''.join(w)
w2=w1.split(' ')
n=w2[0]
words=w2[1:4]
x=w2[4]
k=w2[5]

def duc(s):
    buit=[]
    for i in s:
        buit.append(i)
        buit.sort()
    return buit

def fuc(words):
    prin=[]
    for i in words:
        if (len(i)!=len(x)) or (i==x):
            prin
        elif duc(i)==duc(x):
            prin.append(i)
        else:
            prin
        prin.sort()
    print(len(prin))
    print(prin[int(k)-1])
    
fuc(words)

发表于 2021-01-11 23:59:54 回复(0)
while True:
	try:
		a = input().split()
		n = a[0]
		x = a[-2]
		k = int(a[-1])
		a = a[1:-2]
		m = []
		for i in a:
			if x != i:
				new_i = sorted(i)
				new_x = sorted(x)
				if new_i == new_x:
					m.append(i)
		print(len(m))
		if len(m) >= k: 
			new_m = sorted(m)
			print(new_m[k-1])
	except:
		break
通过了,但是不知道有没有什么漏洞
发表于 2020-12-22 05:26:56 回复(0)
import sys


for s in sys.stdin:
    s = s.strip().split()
    k, x, ws = int(s.pop()), s.pop(), s[1:]
    ws = [w for w in ws if w!=x and sorted(w)==sorted(x)]
    print(len(ws))
    if k < len(ws):
        ws.sort()
        print(ws[k-1])

发表于 2020-12-14 23:41:14 回复(0)
#兄弟单词的判断标准:1.和target单词不同;2.排序后和target单词相同
while True:
    try:
        a = input().split(' ') #
        temp = a[1:-2]          #提取所有要查找的单词
        target = a[-2]            #提取target单词
        index = a[-1]             #提取target单词兄弟单词的index
        res = []                      #res按顺序存储所有的兄弟单词(顺序体现在下一行的sorted(temp))
        for i in sorted(temp):                                   
            if i != target and sorted(i) == sorted(target):   
                res.append(i)
        print(len(res))
        print(res[int(index)-1])         
    except:
        break
发表于 2020-12-11 13:18:33 回复(0)
def brother(letter_list, search_str, index_bro):
    search_list = []
    sort_search_str = ''.join(sorted(search_str))
    for i in letter_list:
        if search_str != i:
            sorted_bro_str = ''.join(sorted(i))
            if sorted_bro_str == sort_search_str:
                search_list.append(i)
    print(len(search_list))
    sort_search_list = sorted(search_list)
    print(sort_search_list[int(index_bro)-1])


while True:
    try:
        a_list = input().split()
        letter_list = a_list[1:-2]
        search_str = a_list[-2]
        index_brother = a_list[-1]
        brother(letter_list, search_str, index_brother)
    except:
        break

发表于 2020-11-28 20:30:58 回复(0)

while True:
    try:
        new_list = []
        list1 = input().split()
        num1 = int(list1.pop())
        str1 = list1.pop()
        num2 = list1.pop(0)
        for x in list1:
            a = ""
            if x != str1:
                if len(x) == len(str1):
                    for y in x:
                        if x.count(y) == str1.count(y):
                            a += y
                    if len(a) == len(x):
                        new_list.append(a)
        new_list.sort()
        print(len(new_list))
        print(new_list[num1-1])
    except:
        break

发表于 2020-11-25 16:01:24 回复(0)
while True:
    try:
        word_nums, *words, lookup_word, bro_num = input().split()
        bro_num = int(bro_num)
        bro_words = []
        for word in words:
            if word == lookup_word:
                continue
            if sorted(word) == sorted(lookup_word):
                bro_words.append(word)
        bro_words.sort()
        print(len(bro_words))
        if bro_words and bro_num <= len(bro_words):
            print(bro_words[bro_num-1])
    except:
        break
发表于 2020-09-26 15:33:58 回复(0)
各位帮忙看看有啥问题,pycharm 正常输出

import sys
line = input()

# 输入处理
strs = line.split(" ")
words = strs[1: -2]
find = strs[-2]
printBrotherIndex = (int(strs[-1]) - 1)

# 查找出与 find 单词全排列相同的单词
# list(str) 对单词进行拆分,sorted(list) 对拆分的单词进行排序
brothers = [word for word in words if sorted(list(word)) == sorted(list(find))]

# 过滤同一单词
brothers = [brother for brother in brothers if brother != find]

# 结果打印
print(len(brothers))
brothers.sort()
if printBrotherIndex < len(brothers):
    print(brothers[printBrotherIndex])
编辑于 2020-09-20 18:59:53 回复(0)
python3解法,想请教下各位大佬,为什么本地IDLE能打印出正确结果,牛客在线输出就为空呢?直接case通过率0,😭😭😭 想破脑袋都没整明白
def brother(s1, s2):
    if s1 == s2:
        return False
    else:
        s1list = sorted([x for x in s1])
        s2list = sorted([y for y in s2])
        if s1list == s2list:
            return True
        return False

line = list(input().split())
n = int(line[0])
s1 = line[-2]
count = 0
sindex = []
finbro = int(line[-1])
for i in range(1,n+1):
    s = line[i]
    if brother(s1, s):
        count += 1
        sindex.append(i)
print(count)
if sindex:
    indexf = sindex[finbro-1]
    print(line[indexf])


发表于 2020-08-26 23:07:28 回复(0)
while True:
    try:
        ss=input().split()
        n=int(ss[0])
        dict=ss[1:n+1]
        s=ss[-2]
        m=int(ss[-1])
        a=[]
        for i in dict:
            if len(i)==len(s) and i!=s and sorted(i)==sorted(s):
                a.append(i)
        print(len(a))
        if a and m<=len(a):
            print(sorted(a)[m-1])
    except:
        break
真的服,题目输出没讲明白,浪费半天调试。。。

发表于 2020-08-09 20:09:03 回复(0)

问题信息

难度:
34条回答 63296浏览

热门推荐

通过挑战的用户

查看代码
查找兄弟单词