这题周末的时候用JAVA写狂RE,吐血了。。调了一个上午都没调出来,当时放弃了,今天想了想还是用C重写吧,谁叫我C++不熟呢,其实用C++的string和map几下就搞定了,C的话只能硬模拟。。这里我用了struct数组排序后二分查找来模拟map,真是蛋疼无比啊。。不过还好C的操作现在比较熟练了,一气呵成没出指针错误,这是万幸,一次AC了,时间竟然比那些C++代码都少。。注意句子处理到最后的时候其实还应该判断下末尾是不是还有单词没打印,如果有的话要打印,但是我把那段代码去掉了还能AC,我就把它删掉了。。毕竟代码越短越好啊,哈哈
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
struct Pair
{
char key[20];
char value[20];
};
static int cmp_char(const void *p1, const void *p2)
{
return *(char *) p1 - *(char *) p2;
}
static int cmp(const void *p1, const void *p2)
{
struct Pair *pp1 = (struct Pair*) p1;
struct Pair *pp2 = (struct Pair*) p2;
return strcmp(pp1->key, pp2->key);
}
int main()
{
struct Pair *array = malloc(10000 * sizeof(struct Pair));
struct Pair *temp = malloc(sizeof(struct Pair));
char s[81];
int index = 0, len;
while (scanf("%s", s), strcmp(s, "DICTIONARY_DEFINE_OVER"))
{
strcpy(array[index].key, s);
strcpy(array[index].value, s);
len = strlen(s);
char *key = array[index].key;
if (len > 2)
qsort(key + 1, len - 2, sizeof(char), cmp_char);
index++;
}
getchar();
qsort(array, index, sizeof(struct Pair), cmp);
int i, si = 0, word = 0;
char *key = temp->key;
while (gets(s) != NULL)
{
for (i = 0; s[i] != '\0'; i++)
{
if (islower(s[i]))
{
word = 1;
key[si++] = s[i];
}
else
{
if (word)
{
key[si] = '\0';
len = strlen(key);
if (len > 2)
qsort(&key[1], len - 2, sizeof(char), cmp_char);
struct Pair *find = bsearch(temp, array, index,
sizeof(struct Pair), cmp);
printf("%s", find->value);
si = 0;
}
word = 0;
putchar(s[i]);
}
}
putchar('\n');
}
free(temp);
free(array);
return 0;
}