首页 > 试题广场 >

查找兄弟单词

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

\hspace{15pt}从字符串的第一个字符开始逐个比较,直到找到第一个不同的位置,通过比较这个位置字符的字母表顺序得出字符串的大小,称为字典序比较。

输入描述:
\hspace{15pt}在一行上:
{\hspace{20pt}}_\texttt{1.}\,先输入一个整数 n \left(1 \leqq n \leqq 1000\right) 代表字符串的个数;
{\hspace{20pt}}_\texttt{2.}\,随后,输入 n 个长度为 1 \leqq {\rm length}(s_i) \leqq 10 ,仅由小写字母构成的字符串 s_1, s_2, \dots, s_n
{\hspace{20pt}}_\texttt{3.}\,随后,输入一个字符串 x
{\hspace{20pt}}_\texttt{4.}\,最后,输入一个整数 k \left(1 \leqq k \leqq n\right) 代表要查找的兄弟单词的序号。


输出描述:
\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 个字符串中。
示例2

输入

3 a aa aaa a 1

输出

0

说明

\hspace{15pt}在这个样例中,按照定义,字符串 \texttt{ 没有兄弟单词。
word = input()
list1 = word.split(" ")
list2 = []
for i in range(int(list1[0])):
    list2.append(list1[i + 1])

list3 = []
for j in list2:
    if sorted(j) == sorted(list1[int(list1[0]) + 1]) and j != list1[int(list1[0]) + 1]:
        list3.append(j)

count = len(list3)
sort_value = sorted(list3)

print(count)
if int(list1[int(list1[0]) + 2]) <= count:
    print(sort_value[int(list1[int(list1[0]) + 2]) - 1])

编辑于 2024-03-20 11:51:56 回复(0)
# 判断是否是兄弟单词
# 字典排序后相等,但原字符串不等
def is_bro(a: str, b: str):
    if a == b:
        return False
    if sorted(a) == sorted(b):  
        return True

while True:
    try:
        arr = input().split()
        s = arr[-2]  # 比较字符串
        n = int(arr[0])  # 需要匹配的字符串个数
        bro_list = []  # 兄弟字符串 列表

        for j in range(1, n + 1):
            if is_bro(s, arr[j]):
                # 是兄弟,就加一
                bro_list.append(arr[j])

        print(len(bro_list))
        bro_list = sorted(bro_list)
        print(bro_list[int(arr[-1]) - 1])
       
    except:
        break

编辑于 2024-03-08 09:21:43 回复(0)
一个笨方法,建立一个字典记录被查找的单词,遍历时再建立一个临时字典
while True:
    try:
        lst = input().split()
        lst1 = []
        num_1 = int(lst[0])
        num_2 = int(lst[-1])
        hash = {}
        for i in range(len(lst[-2])):
            if lst[-2][i] not in hash:
                hash[lst[-2][i]]=1
            else:
                hash[lst[-2][i]] += 1
        for i in range(1, num_1 + 1):
            if lst[i] == lst[-2]:
                continue
            else:
                hash1 = {}
                for j in range(len(lst[i])):
                    if lst[i][j] not in hash1:
                        hash1[lst[i][j]] = 1
                    else:
                        hash1[lst[i][j]] +=1
                if hash==hash1:
                    lst1.append(lst[i])
        print(len(lst1))
        print(sorted(lst1)[num_2 - 1])
    except:
        break

编辑于 2024-01-19 10:44:15 回复(0)
all_char=input()
all_char=all_char.split(' ')
all_len=len(all_char)
N=eval(all_char[0])
candidate =all_char[1:all_len-2]
search_char=all_char[all_len-2]
k=eval(all_char[all_len-1])
search_char_sort=sorted(search_char)
count=0
brother_char=[]
for c in candidate:
    if c!=search_char:
        c_sort=sorted(c)
        if c_sort==search_char_sort:
            count+=1
            brother_char.append(c)
print(count)
brother_char=sorted(brother_char)
if k<=len(brother_char):
    print(brother_char[k-1])

发表于 2023-08-01 15:18:45 回复(0)
while 1:
    try:
        ls = input().split()
        n = int(ls[0])
        k = int(ls[-1])
        x = ls[-2]
        l = ls[1 : n + 1]
        co = 0
        p = []
        for i in l:
            if i != x and sorted(i) == sorted(x):
                p.append(i)
                co += 1
        p.sort()
        print(co)
        if p[k - 1]:
            print(p[k - 1])
    except:
        break


发表于 2023-07-26 17:53:46 回复(0)
说了一大堆,兄弟的意思不就是这个吗?
if i != x and sorted(x) == sorted(i):
你们看我这个简单吗?
s = input().split()
x = s[-2]
k = int(s[-1])
h = s[1:-2]
bro = []
for i in h:
    if i != x and sorted(x) == sorted(i):
        bro.append(i)
j = len(bro)
if j < k:
    print(j)
else:
    new_bro = sorted(bro)
for i in range(j):
    if i+1 == k:
        print(j)
        print(new_bro[i])




发表于 2023-04-07 21:45:13 回复(0)
import sys

def find_brother_word(brother_word: list, x_word: str) -> list:
    x_word_dic = {}
    for s in x_word:
        if s not in x_word_dic:
            x_word_dic[s] = 1
        else:
            x_word_dic[s] = x_word_dic[s] + 1

    brother_list = []
    for item in brother_word:
        brother_dic = {}
        for s in item:
            if s not in brother_dic:
                brother_dic[s] = 1
            else:
                brother_dic[s] = brother_dic[s] + 1

        if item != x_word and brother_dic == x_word_dic:
            brother_list.append(item) 
    return brother_list

if __name__ == '__main__':
    for line in sys.stdin:
        a = line.split()

    brother_word_num = int(a[0])
    brother_word = a[1:(brother_word_num + 1)]
    x_word_num = int(a[-1])
    x_word = a[-2]
    brother_list = find_brother_word(brother_word, x_word)
    brother_list.sort()
    print(len(brother_list), end='\n')
    if len(brother_list) >= x_word_num:
        print(brother_list[x_word_num-1])

发表于 2023-03-28 20:57:19 回复(0)
import sys

#for line in sys.stdin:
#   a = line.split()
#   print(int(a[0]) + int(a[1]))

#先求出dict1关键字字典,x的值,和k的值
s=input()
L = s.split()
y=L[-2]
n = int(L[0])
dict1 = L[1:n+1]
#dict1 = list(set(dict1))
list1 = list(L[-2])
k =int(L[-1])
L2=0
#s = "3 abc bca cab abc 1"
# L = s.split()
# n = int(L[0])
# dict1 = L[1:n+1]
# x = L[-2]
# k = L[-1]

# def func(x):
#    L2 = []
#    for i in x:
#       if len(x) == 1:
#            return x
#        else:
#           # s = i + func(x[1:], L2)
#           # L2.append(s)
#            x = x[]
#            s = i + func(x[1:])
#       L2.append(s)
# L2 = func(x)
# print(L2)
# /usr/bin/env

# 递归不建议,一层层的看调试,递归的路径比较深
# list作为可选元素,stack作为已走路径
def perm(liststack,L2):
    # 遍历结束的条件是叶子节点,即List为空,即可选路径为空
    if not list:
        # 到树的最后,输出结果,我们只需要已走路径
        #print(stack)
        L2.append(stack.copy())
    else:
        for i in range(len(list)):
        # 做出决策
            stack.append(list[i])
            del list[i]
        # 进行递归
            perm(list, stack,L2)
        # 退回决策
            list.insert(i, stack.pop())
    return L2

#dict1 = ["a", "b", "c"]
stack = []
L2=[]
L3=[]
L2=perm(list1, stack,L2)
L4=[]
for x in L2:
    x="".join(x)
    L4.append(x)
#print(y)
L4.remove(y)

for x in dict1:
    if x in L4:
        L3.append(x)
    else:
        pass
#print(L3)
print(len(L3))

#需要考虑k的值比列表中的元素多的情况
try:
    if L3[k-1]:
        print(L3[k-1])
    else:
        pass
except:
    pass





发表于 2023-02-11 11:37:47 回复(3)
# 判断单词s1和s2是否是兄弟单词 0否 1是
def is_brother(s1,s2):
    n1,n2=len(s1),len(s2)
    if n1!=n2:
        return 0
    if n1==n2:
        L1={x:0 for x in s1}
        L2={x:0 for x in s2}
        for x in s1:
            L1[x]+=1
        for x in s2:
            L2[x]+=1
        if sorted(L1.items())==sorted(L2.items()) and s1!=s2:
            return 1
        else:
            return 0

while True:
    try:
        S0=input().split()
        n=int(S0[0]) 
        x=S0[-2]
        k=int(S0[-1])
        S=S0[1:n+1]
        L=[] #记录兄弟单词

        for a in S:
            if is_brother(x,a)==1:
                L.append(a)

        n=len(L)
        print(n)
        if n>=k:
            L1=sorted(L)
            print(L1[k-1])
    except:
        break




发表于 2023-02-08 10:15:38 回复(0)
a = input().split()
b = a[1 : len(a) - 2]  # n个单词
x = a[len(a) - 2]
x_len = len(x)
w = 0  # 兄弟字母的个数
t = []
for i in b:
    if len(i) == x_len:
        if i == x:
            continue
        else:
            m = 0
            for n in i:
                if n in x and i.count(n) == x.count(n):
                    m += 1
                else:
                    continue
            if m == x_len:
                w += 1
                t.append(i)
    else:
        continue
print(w)
t1 = sorted(t, key=lambda x: x)
if len(t1) > int(a[-1]):
    print(t1[int(a[-1]) - 1])

发表于 2023-01-15 20:28:09 回复(0)
a = input().split()
a1 = a[0]
a2 = a[-1]
a3 = a[-2]
aa = a[1:-2]
d = 0
e = []
for b in aa:
    if len(b) == len(a3):
        for c in range(len(a3)):
            if a3[c] in b and b.count(a3[c]) == a3.count(a3[c]):
                pass
            else:
                break
            if c == len(a3)-1 and b != a3:
                d += 1
                e.append(b)
print(d)
try:
    print(sorted(e)[int(a2)-1])
except:
    pass

发表于 2022-12-18 13:25:16 回复(0)
while True:
    try:
        s = input().split(" ")
        word_dic, ref, k = s[1:-2], s[-2], int(s[-1])
        # 判断是否为兄弟单词
        tmp = []
        for item in word_dic:
            if item != ref and sorted(item) == sorted(ref):
                tmp.append(item)
        print(len(tmp))
        print(sorted(tmp)[k-1])
    except:
        break


题目关键点:
1、对输入的处理
2、比较时的关键点在于只要字母组成一致顺序不同就是”兄弟单词“
3、将兄弟单词加入到结果列表中。输出列表的长度和列表对应位置上的元素即可
发表于 2022-11-29 16:42:07 回复(0)
只过了60%
有用例输入无法复制... 

import sys

def main():
    line = sys.stdin.readline().strip().split()
    quantity = int(line[0])
    chars = line[1:quantity+1]
    pattern = line[-2]
    reqindex = int(line[-1])

    # print(chars)
    result=[]

    for each in chars:
        if len(each) != len(pattern):
            continue
        tmpeach=each
        for c in pattern:
            tmpeach = tmpeach.replace("{}".format(c),'',1)

        if len(tmpeach) >0:
            continue
        else:
            result.append(each)

    if pattern in result:
        result.remove(pattern)
    result.sort()
    # print(result)
    length = len(result)
    print(length)
    if length >= reqindex:
        print(result[reqindex-1])
    else:
        pass

if __name__ == '__main__':
    main()

发表于 2022-10-03 18:23:02 回复(0)
input_info = input()
info_list = input_info.split(" ")
words = info_list[1:-2]
x = info_list[-2]
k = int(info_list[-1])

_dict = [
    word for word in words if (x != word) and sorted(list(x)) == sorted(list(word))
]
_dict.sort()
try:
    print(len(_dict))
    print(_dict[k - 1])
except:
    pass
发表于 2022-09-25 20:27:03 回复(0)
lst=input().split()[1:]
lst1=lst[:-1]
n=int(lst[-1])
st=""
lst2=sorted(lst1[-1])
num=0
lst3=[]
for i in lst1[:-1]:
    if i!=lst1[-1] and sorted(i)==lst2:
        num+=1
        lst3.append(i)
print(num)
lst3=sorted(lst3)
if len(lst3)>=n:
    print(lst3[n-1])
发表于 2022-09-13 20:55:14 回复(0)
while True:
    try:
        ls = [i for i in input().split(" ")]
        n, candidates, target, k = int(ls[0]), ls[1:int(ls[0])+1], ls[int(ls[0])+1], int(ls[-1])
        res = 0
        tem = []
        for item in candidates:
            if sorted(item) == sorted(target) and item != target:
                res += 1
                tem.append(item)
        tem = sorted(tem)
        print(res)
        if k <= len(tem):
            print(tem[k-1])
    except:
        break

发表于 2022-09-13 03:52:59 回复(0)
lst_in=list(input().split())
lst=[]
n=int(lst_in[0])
x,k=lst_in[n+1],int(lst_in[-1])
for item in lst_in[1:n+1]:
    if item!=x and sorted(item)==sorted(x):
        lst.append(item)
print(len(lst))
if len(lst)>=k:
    lst.sort()
    print(lst[k-1])

发表于 2022-09-07 16:13:13 回复(0)