Day3 D - Anagram


题目正文

You are to write a program that has to generate all possible words from a given set of letters.
Example: Given the word “abc”, your program should - by exploring all different combination of the three letters - output the words “abc”, “acb”, “bac”, “bca”, “cab” and “cba”.
In the word taken from the input file, some letters may appear more than once. For a given word, your program should not produce the same word more than once, and the words should be output in alphabetically ascending order.
Input
The input consists of several words. The first line contains a number giving the number of words to follow. Each following line contains one word. A word consists of uppercase or lowercase letters from A to Z. Uppercase and lowercase letters are to be considered different. The length of each word is less than 13.
Output
For each word in the input, the output should contain all different words that can be generated with the letters of the given word. The words generated from the same input word should be output in alphabetically ascending order. An upper case letter goes before the corresponding lower case letter.

翻译

您要编写一个程序,该程序必须从给定的一组字母生成所有可能的单词。

示例:给定“abc”一词,您的程序应该——通过探索三个字母的所有不同组合——输出“abc”、“acb”、“bac”、“bca”、“cab”和“cba”一词。

在从输入文件中提取的单词中,某些字母可能会出现多次。对于给定的单词,您的程序不应多次生成同一单词,并且单词应按字母升序输出。

输入

输入由几个单词组成。第一行包含一个数字,给出了后面的字数。以下每行包含一个单词。单词由从A到Z的大写或小写字母组成。大写字母和小写字母应视为不同。每个单词的长度小于13。

输出

对于输入中的每个单词,输出应该包含可以用给定单词的字母生成的所有不同单词。从同一输入单词生成的单词应按字母升序输出。大写字母在相应的小写字母之前。

样例

3
aAb
abc
acba

扫描二维码关注公众号,回复: 13303513 查看本文章

Aab
Aba
aAb
abA
bAa
baA
abc
acb
bac
bca
cab
cba
aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa

代码

代码:

//1.定义一个字符数组
//2.自定义一个比较函数返回值为bool,传入两个参,运用tolower函数,如果相等返回字母本身
//3.否则返回asiic大的值
//4.在主函数里定义测试用例,并输入,输出字符,用sort进行自定义排序,do-while循环输出
//条件是全排列next_permutation(str,str+strlen(str),cmp)
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<string.h>
using namespace std;

char str[100];
bool cmp(char a,char b)
{
    
    
    if(tolower(a)==tolower(b))
        return a<b;
    else
        return tolower(a)<tolower(b);
}
int main()
{
    
    
    int T;
    cin>>T;
    while(T--)
    {
    
    
        cin>>str;
        sort(str,str+strlen(str),cmp);
        do
        {
    
    
            cout<<str<<endl;
        }while(next_permutation(str,str+strlen(str),cmp));
    }
    return 0;
}

总结

其实这题是一个全排列问题,只需要运用函数next_permutation,就能完成,但是题目中还有要求一个大写字母在小写字母前面,就加上了一个自定义函数,若转换为小写字母相同时,就返回ASCII小的,即大写字母,就可以完成要求了。

猜你喜欢

转载自blog.csdn.net/MarigoldLi/article/details/119343797