题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
直接看代码:
#include <stdio.h>
#include <string.h>
int char_count(char *str, char ch)
{
int count = 0;
int len = strlen(str);
for(int i = 0; i < len; i++)
{
if(ch == str[i])
count++;
}
return count;
}
int judge_brother(char *ptr1, char *ptr2)
{
int len = strlen(ptr1);
for(int i = 0; i < len; i++)
{
if(char_count(ptr1, ptr1[i]) != char_count(ptr2, ptr1[i]))
return 0;
}
return 1;
}
int compare(char *ptr1, char *ptr2)
{
int len = strlen(ptr1) > strlen(ptr2) ? strlen(ptr2) : strlen(ptr1);
for(int i = 0; i < len; i++)
{
if(ptr1[i] > ptr2[i])
return 1;
else if(ptr1[i] < ptr2[i])
return -1;
}
if(strlen(ptr1) == strlen(ptr2))
return 0;
else if(strlen(ptr1) > strlen(ptr2))
return 1;
return -1;
}
int swap(char *ptr1, char *ptr2)
{
char temp;
int len = strlen(ptr1) > strlen(ptr2) ? strlen(ptr1) : strlen(ptr2);
for(int i = 0; i < len + 1; i++)
{
temp = ptr1[i];
ptr1[i] = ptr2[i];
ptr2[i] = temp;
}
return 0;
}
int main(void)
{
int cnt = 0;
int i, n, m, len;
char word[32];
char words[1024][32];
char brother[1024][32];
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%s", words[i]);
}
scanf("%s", word);
scanf("%d", &m);
len = strlen(word);
for(i = 0; i < n; i++)
{
if(len != strlen(words[i]))
continue;
if(0 == strcmp(word, words[i]))
continue;
if(judge_brother(word, words[i]))
{
for(int j = 0; j < len+1; j++)
brother[cnt][j] = words[i][j];
cnt++;
}
}
for(i = 0; i < cnt; i++)
{
for(int j = i + 1; j < cnt; j++)
{
if(compare(brother[i], brother[j]) > 0)
swap(brother[i], brother[j]);
}
}
printf("%d\n", cnt);
if(m < cnt)
printf("%s\n", brother[m-1]);
return 0;
}