描述
定义一个单词的“兄弟单词”为:交换该单词字母顺序(注:可以交换任意次),而不添加、删除、修改原有的字母就能生成的单词。
兄弟单词要求和原来的单词不同。例如: ab 和 ba 是兄弟单词。 ab 和 ab 则不是兄弟单词。
现在给定你 n 个单词,另外再给你一个单词 x ,让你寻找 x 的兄弟单词里,按字典序排列后的第 k 个单词是什么?
注意:字典中可能有重复单词。
数据范围:1≤n≤1000 ,输入的字符串长度满足 1≤len(str)≤10 ,1≤k<n
输入描述:
输入只有一行。 先输入字典中单词的个数n,再输入n个单词作为字典单词。 然后输入一个单词x 最后后输入一个整数k
输出描述:
第一行输出查找到x的兄弟单词的个数m 第二行输出查找到的按照字典顺序排序后的第k个兄弟单词,没有符合第k个的话则不用输出。
示例1
输入:
3 abc bca cab abc 1
输出:
2 bca
示例2
输入:
6 cab ad abcd cba abc bca abc 1
输出:
3 bca
说明:
abc的兄弟单词有cab cba bca,所以输出3 经字典序排列后,变为bca cab cba,所以第1个字典序兄弟单词为bca
#include <stdio.h>
#include <string.h>
int main() {
int n; //字典中的单词个数
char dict[1000][1000]; //单词字典
char str[11]; //待查找单词
int k; //str的第k个兄弟单词
// 1.输入
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%s ",dict[i]);
}
scanf("%s",str);
scanf("%d",&k);
// 2.构建待查找单词的哈希表
int hash[26]; //待查找单词的哈希表
int index;
int L=strlen(str);
// 2.1 初始化
for(int i=0;i<26;i++)
{
hash[i]=0;
}
// 2.2 构建待查找单词哈希表
for(int i=0;i<L;i++)
{
index = str[i]-97;
hash[index]++;
}
// 3.构建字典中单词的哈希表
int flag[1000]; //用于判断该单词是否是兄弟单词
int hash_[1000][26];
// 3.1 初始化
for(int i=0;i<n;i++)
{
flag[i]=0; //值为L-是兄弟单词,其他值-不是兄弟单词
for(int j=0;j<26;j++)
{
hash_[i][j]=0;
}
}
// 3.2 构建字典中与待查找单词不相等的单词的哈希表
for(int i=0;i<n;i++) //遍历字典中的单词
{
for(int j=0;j<strlen(dict[i]);j++)//统计字典单词中出现的字母及次数
{
index=dict[i][j]-97;
hash_[i][index]++;
}
}
// 4.判断哪些是兄弟单词,统计兄弟单词的个数
int count=0;
char find_brother[1000][1000];
int l=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<26;j++)
{
if(hash[j] == hash_[i][j])
{
flag[i]++;
}
}
if(strcmp(dict[i],str)!=0 && flag[i]==26)//如果与待查找单词不相同,且hash表相同,则是兄弟单词
{
count++;
strcpy(find_brother[l], dict[i]);
l++;
}
}
// 5.对所有兄弟单词按照字典排序
char temp[11];
for(int i=0;i<l-1;i++)
{
for(int j=0;j<l-i-1;j++)
{
if(strcmp(find_brother[j], find_brother[j+1])>0)
{
strcpy(temp, find_brother[j]);
strcpy(find_brother[j], find_brother[j+1]);
strcpy(find_brother[j+1], temp);
}
}
}
// 6.输出
printf("%d\n%s",count,find_brother[k-1]);
return 0;
}