题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
//*xtj
#include<stdio.h>
#include<string.h>
int isbrother(char* next, int lenth);
int letter[100] = { 0 };
int len = 0;
char obj[100];
int main()
{
int n = 0, k = 0;
char word[1000][100];
char Bword[1000][100];
while(scanf("%d", &n)!=EOF)
{
for (int i = 0; i < n; i++)
{
scanf("%s", word[i]);
}
scanf("%s", obj);//输入目标单词
scanf("%d", &k);//输入第k个
//shurujiesu
int count = 0;
len = strlen(obj);
for (int i = 0; i < len; i++)
{
letter[obj[i] - 'a']++;;//判断obj中含有什么字母
}
int m = 0;//含有的兄弟单词数量
for (int i = 0; i < n; i++)
{
if (isbrother(word[i], strlen(word[i])))
{
strcpy(Bword[m++],word[i]);
}
}
printf("%d\n", m);//输出单词个数
for (int i = 0; i < m - 1; i++)//排序
{
for (int j = i + 1; j < m; j++)
{
if (strcmp(Bword[i], Bword[j]) >=0)//从小到大排序
//!!!!务必认真仔细,这个地方不是难点,我本应该不会错
//却因为>=0写成了>1,导致最后一个算例做错,检查了很久都没有检查出来
{
char temp[100];
strcpy(temp, Bword[j]);
strcpy(Bword[j], Bword[i]);
strcpy(Bword[i], temp);
}
}
}
if (k <= m)
{
printf("%s", Bword[k - 1]);
}
}
return 0;
}
int isbrother(char* next, int lenth)
{
if (lenth != len)
return 0;//长度不同不是
if (!strcmp(next, obj))
return 0;//完全相同的不是
int let2[100] = { 0 };
for (int i = 0; i < lenth; i++)
{
if (!letter[next[i] - 'a'])
return 0;//含有没有的字母不是
let2[next[i] - 'a']++;;//判断next中含有什么字母,及其个数
}
for (int i = 0; i < 26; i++)
{
if (let2[i] != letter[i])
{
return 0;//含有某字母个数不一样
}
}
return 1;//通过考察,是兄弟单词
}
//*/ 写代码时务必认真仔细,不能因为简单的功能就粗心!
不然代码小错误很难发现,排查需要浪费大量时间!!!
