Algorithm --> 字母重排

字母重排

  输入一个字典(用***结尾),然后再输入若干单词。没输入一个单词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[2000][10], sorted[2000][10];

//字符比较函数
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 = 0;
    while(true)
    {
        cin >> word[n];
        if(word[n][0] == '*') break;                             //遇到结束标注就终止
        n++;
    }
    qsort(word, n, sizeof(word[0]), cmpString);               //给所有单词排序
    for(int i = 0; i < n; i++)
    {
        strcpy(sorted[i], word[i]);
        qsort(sorted[i], strlen(sorted[i]), sizeof(char), cmpChar);  //给每个单词排序
    }
    
    char s[10];
    while(cin >> s)                              //读取字符串
    {
        qsort(s, strlen(s), sizeof(char), cmpChar);           //给输入单词排序
        bool found = false;
        for(int i = 0; i < n; i++)
        {
            if(!strcmp(sorted[i], s))
            {
                found = true;
                cout << word[i] << " ";                  //输出原始单词,而不是排序后的
            }
        }
        if(!found) cout << ":(";
        cout << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jeakeven/p/4630841.html