判断两个字符集是否相同

【问题描述】

从标准输入中读入两个字符集(不包含空格、制表符、回车换行等空白字符),字符集中的字符无序,且可能有重复字符。当两个字符集中字符完全相同(字符相同,字符若重复,重复个数也相同,顺序不一定相同),则两个字符集相同。编写一程序判断输入的两字符集是否相同:用1表示相同,用0表示不同。

【输入形式】

分别在两行上输入两个字符集(每个字符集中的字符个数不超过20,且第二个字符集输入结束后也有回车换行)。

【输出形式】

若两字符集相同,则输出1,否则输出0,然后按照从小到大的顺序分行输出第一个字符集中的字符及重复个数(以一个空格分隔)。

【样例输入1】

helloworld9
worldhello9

【样例输出1】

1
9   1
d   1
e   1
h   1
l   3
o   2
r   1
w   1

【样例输入2】

helloworld
heloworld

【样例输出2】

0
d   1
e   1
h   1
l   3
o   2
r   1
w   1

【样例说明】

样例1中输入的两个字符集的字符和各个字符的重复个数都完全相同,所以输出1,然后按从小到大的顺序输出第一个字符集中各字符及重复个数(即:有1个9,1个d,1个e,1个h,3个l,2个o,1个r,1个w)。
样例2中输入的两个字符集中的字符相同,但第一个字符集中有3个l,而第二个数据集中有2个l,所以两个字符集不同,输出0,并按从小到大的顺序输出第一个字符集中的各字符及重复个数。

【评分标准】

该题要求判断两字符集是否相同,共有5个测试点。上传C语言文件名为example2b.c。

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <stdlib.h>
#include <cstdlib>
#include <string.h>
#include <string>
#include <cmath>
#include <map>
#include <time.h>
using namespace std;
map<char, int> mymap1;
map<char, int> mymap2;
int main() {
    char a[100];
    char b[100];
    cin >> a;
    cin >> b;
    for (int i = 0; a[i] != '\0'; i++) {
        mymap1[a[i]]++;
    }
    for (int i = 0; b[i] != '\0'; i++) {
        mymap2[b[i]]++;
    }

    if (strlen(a) != strlen(b) || mymap1.size()!=mymap2.size()) {
        cout << "0\n";
    }
    else {
        map<char, int>::iterator it = mymap1.begin();
        map<char, int>::iterator itt = mymap2.begin();
        int flag = 1;
        while (it != mymap1.end() || itt != mymap2.end()) {
            if (it->first != itt->first || it->second != itt->second) {
                flag = 0;
                break;
            }
            it++;
            itt++;
        }
        cout << flag <<endl;
    }
    map<char, int>::iterator it = mymap1.begin();
    while (it != mymap1.end())
    {
        cout << it->first << " " << it->second << endl;
        it++;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/woxiaosade/p/10472720.html