Algorithm --> 字母重排

时间:2021-07-31 03:36:29

字母重排

  输入一个字典(用***结尾),然后再输入若干单词。没输入一个单词w,都需要在字典中找出所有可以用w的字幕重排后得到的单词,并按照字典序从小到大的顺序在一行中输出,如果不存在,输出“:(”。单词间用空格隔开,且所有输入单词都由不超过6个小写字母组成。

样例输入:
tarp given score refund only trap work earn course *****
aptr asdfg
样例输出:
part tarp trap
:(

程序:

#include <iostream>
#include <cstring>
//#include <stdio.h>
#include <stdlib.h>
using namespace std; char word[][], sorted[][]; //字符比较函数
int cmpString(const void *a, const void *b)
{
return strcmp((char*)a, (char*)b);
} //字符串比较函数
int cmpChar(const void *a, const void *b)
{
return *(char*)a - *(char*)b;
} int main()
{
int n = ;
while(true)
{
cin >> word[n];
if(word[n][] == '*') break;        //遇到结束标注就终止
n++;
}
qsort(word, n, sizeof(word[]), cmpString);            //给所有单词排序
for(int i = ; i < n; i++)
{
strcpy(sorted[i], word[i]);
qsort(sorted[i], strlen(sorted[i]), sizeof(char), cmpChar); //给每个单词排序
} char s[];
while(cin >> s)                            //读取字符串
{
qsort(s, strlen(s), sizeof(char), cmpChar);          //给输入单词排序
bool found = false;
for(int i = ; i < n; i++)
{
if(!strcmp(sorted[i], s))
{
found = true;
cout << word[i] << " ";                 //输出原始单词,而不是排序后的
}
}
if(!found) cout << ":(";
cout << endl;
}
return ;
}