输入一个字典(用******结尾),然后再输入若干单词。每输入一个单词w,你都需要在字典中找出所有可以用w的字母重排后得到的单词,并按照字典序从小到大的顺序在一行中输出(如果不存在,输出:()。输入单词之间用空格或空行隔开,且所有输入单词都由不超过6个小写字母组成。注意,字典中的单词不一定按字典序排列。
样例输入:
tarp given score refund only trap work earn course pepper part
******
resco nfudre aptr sett oresuc
样例输出:
score
refund
part trap trap
:(
样例输入:
tarp given score refund only trap work earn course pepper part
******
resco nfudre aptr sett oresuc
样例输出:
score
refund
part trap trap
:(
course
原书代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int n;
char word[2000][10], sorted[2000][10];
int cmp_char(const void* _a, const void* _b)
{
char* a = (char*)_a;
char* b = (char*)_b;
return *a - *b;
}
int cmp_string(const void* _a, const void* _b)
{
char* a = (char*)_a;
char* b = (char*)_b;
return strcmp(a, b);
}
int main()
{
FILE *fp = fopen("chen.txt","r");
n = 0;
for(;;)
{
fscanf(fp,"%s", word[n]);
if(word[n][0] == '*') break;
n++;
}
qsort(word, n, sizeof(word[0]), cmp_string);
for(int i = 0; i < n; i++)
{
strcpy(sorted[i], word[i]);
qsort(sorted[i], strlen(sorted[i]), sizeof(char), cmp_char);
}
char s[10];
while(fscanf(fp,"%s", s) == 1)
{
qsort(s, strlen(s), sizeof(char), cmp_char);
int found = 0;
for(int i = 0; i < n; i++)
if(strcmp(sorted[i], s) == 0)
{
found = 1;
printf("%s ", word[i]);
}
if(!found) printf(":(");
printf("\n");
}
return 0;
}
上面代码中:
strcmp(sorted[i], s) == 0 不行,因为重新排序后有的单词可能出现重复的字符,造成不会相等,如: sett 和 set 是满足条件的,但是不会被程序找到
修改后的代码:
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
using namespace std;
int main()
{
string str[200];
int count = 0;
ifstream f("chen.txt");
while( f >> str[count])
{
if(str[count][0] == '*')
break;
count ++;
}
sort(str,str+count);
string tmp;
while( f >> tmp )
{
bool sig = 0;
for(int i = 0; i < count; ++i)
if(str[i].find_last_not_of(tmp) == -1 && tmp.find_last_not_of(str[i]) == -1)
{
cout << str[i] << " ";
sig = 1;
}
if(sig == 0)
cout << ":(";
cout << endl;
}
return 0;
}