题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <string.h>
#define INPUT_STR_LEN 11
#define LETTER_BASE 97
int n;//单词数
char dic[1000][INPUT_STR_LEN] = {0}; //所有单词的字典
unsigned char letter[26] = {0}; //字典单词的字母收集,用于和目标单词的对比
char aim_word[INPUT_STR_LEN];//目标单词
unsigned char aim_word_len = 0;//目标单词的长度
unsigned char letter_aim[26] = {0}; //目标单词的字母收集
int brother_num = 0; //兄弟单词的数量
char dic_brother[1000][INPUT_STR_LEN] = {0};//兄弟单词的字典
int main(void)
{
int dic_word_len = 0 ,k;
//字典读入
scanf("%d",&n);
for(int i = 0; i < n; i++)
scanf("%s",&dic[i]);
//目标单词读入和字母拆解
scanf("%s %d",&aim_word,&k);
aim_word_len = strlen(aim_word);
for(int i = 0; i < aim_word_len; i++)
letter_aim[aim_word[i] - LETTER_BASE] ++;
//筛选出兄弟单词
for(int i = 0; i < 1000; i++)
{
dic_word_len = strlen(dic[i]);
//初步筛选,长度一致且不是同一个单词
if(dic_word_len == aim_word_len && strcmp(dic[i],aim_word))
{
//拆解出字母
for(int j = 0; j < dic_word_len; j++)
letter[dic[i][j] - LETTER_BASE] ++;
//单词的字母一致
if(!memcmp(letter,letter_aim,26))
{
strcpy(dic_brother[brother_num],dic[i]);
brother_num ++;
}
memset(letter,0,26);
}
}
//冒泡
char word_temp[INPUT_STR_LEN];
for(int i = 0; i < brother_num-1; i++)
for(int j = 0; j < brother_num-1-i; j++)
if(strcmp(dic_brother[j],dic_brother[j+1]) > 0)
{
strcpy(word_temp,dic_brother[j]);
strcpy(dic_brother[j],dic_brother[j+1]);
strcpy(dic_brother[j+1],word_temp);
}
//输出
printf("%d\n",brother_num);
if(0 <= k && k <= brother_num)
printf("%s",dic_brother[k-1]);
return 0;
}