题解 | #查找兄弟单词#
查找兄弟单词
http://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68
这题的描述有点离谱了。说得绕不说,对于字典里的重复兄弟单词的处理也没说,样例也没写。亏我第一时间以为要排除掉重复单词,毕竟是困难难度嘛。结果还真就没要求排除。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int compare(char x[], int charinput[]);
int strcompare(const void *x, const void *input);
int main(){
int n=0;
char *dictionary[1000]={NULL};//字典指针集
char input[11]={0};
int k=0;
while(scanf("%d", &n)==1){
getchar();//吸收空格
//输入环节
//以小存储单元形式储存
for(int i=0; i<n; i++){
char *p;
p=(char *)malloc(11*sizeof(char));
scanf("%s", p);
dictionary[i]=p;
}
scanf("%s", input);
scanf("%d", &k);
//处理环节
//筛选兄弟单词
//准备阶段
int charinput[26]={0};
for(int i=0; i<10&&input[i]!=0; i++){
charinput[input[i]-'a']++;
}
char *dictionary2[1000]={NULL};
int j=0;
//开始筛选
for(int i=0; i<n; i++){
if(compare(dictionary[i], charinput)==0){
dictionary2[j++]=dictionary[i];
}
}
//按字典顺序排序
qsort(dictionary2, j, sizeof(char *), strcompare);
//排除重复
int count=j;
for(int i=0; i<j; i++){
if(strcmp(dictionary2[i], input)==0){
count--;
dictionary2[i]=NULL;
}
}
printf("%d\n", count);
int i=0;
int i2=0;
for( ; i<n; i++){
if(dictionary2[i]!=NULL) {
i2++;
}
if(i2==k) break;
}
if(i2==k) printf("%s\n", dictionary2[i]);
}
return 0;
}
int strcompare(const void *x, const void *y){
return strcmp(*(char **)x, *(char **)y);
}
int compare(char x[], int charinput[]){
int charx[26]={0};
for(int i=0; i<10&&x[i]!=0; i++){
charx[x[i]-'a']++;
}
return memcmp(charinput, charx, 26*sizeof(int));
}
查看7道真题和解析