题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//困难,手动狗头
//照着题目意思硬走了一遍,感觉解法有点投机
//首先全是小写字母,可以用hash表比较是否兄弟单词(提前排除相等情况)
//其次C99初始化带参数字符数组要多写一句就定义了1000;
//最后用qsort排序字符串输出就好啦
//有排序函数还是好用,不用每次都冒泡选择快排写重组造轮子
int hash_cmp(char *s, char *t);
int cmp_char(const void *_a, const void *_b);
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
char word[n][11];
for (int i = 0; i < n; i++)
{
scanf("%s", word[i]);
}
char str[10];
scanf("%s", str);
int k;
scanf("%d", &k);
int count = 0;
char bro_word[1000][11] = {'\0'};
//用简单hash表进行比较
for (int i = 0; i < n; i++)
{
if (strcmp(str, word[i]) != 0)
{
if (hash_cmp(str, word[i]) == 0)
strcpy(bro_word[count++], word[i]);
}
}
//count个兄弟 0-count-1;
printf("%d\n", count);
if (k <= count)
{
qsort(bro_word, count, sizeof(bro_word[0]), cmp_char);
printf("%s\n", bro_word[k - 1]);
}
}
return 0;
}
int hash_cmp(char *s, char *t)
{
int ret = 0;
// 0兄弟
int hash[26] = {0};
for (int i = 0; i < strlen(s); i++)
{
hash[s[i] - 'a']++;
}
for (int i = 0; i < strlen(t); i++)
{
hash[t[i] - 'a']--;
}
for (int i = 0; i < 26; i++)
if (hash[i] != 0)
{
ret = 1;
break;
}
return ret;
}
int cmp_char(const void *_a, const void *_b)
{
char *a = (char *)_a;
char *b = (char *)_b;
return strcmp(a, b);
}