首页 > 学院 > 开发设计 > 正文

算法训练 Anagrams问题

2019-11-10 22:08:05
字体:
来源:转载
供稿:网友
算法训练 Anagrams问题  时间限制:1.0s   内存限制:512.0MB    问题描述  Anagrams指的是具有如下特性的两个单词:在这两个单词当中,每一个英文字母(不区分大小写)所出现的次数都是相同的。例如,“Unclear”和“Nuclear”、“Rimon”和“MinOR”都是Anagrams。编写一个程序,输入两个单词,然后判断一下,这两个单词是否是Anagrams。每一个单词的长度不会超过80个字符,而且是大小写无关的。  输入格式:输入有两行,分别为两个单词。  输出格式:输出只有一个字母Y或N,分别表示Yes和No。  输入输出样例样例输入UnclearNuclear样例输出Y

思路:

把简单的事情搞得有点复杂了,用map写到一半才知道sort不能对他用键值排序,晕。

代码:

#include<iostream>#include<string>#include<cstring>#include<map>#include<algorithm>using namespace std;map<int,int> ans;map<int,int> bns;int main(){    string s1,s2;    cin>>s1>>s2;    int len_s1=s1.length();    int len_s2=s2.length();    if(len_s1!=len_s2)    {        PRintf("N/n");        return 0;    }    for(int i=0;i<len_s1;i++)    {        if(!islower(s1[i]))            s1[i]=tolower(s1[i]);        int num=s1[i];        map<int,int>::iterator it;        int flag=0;        for(it=ans.begin();it!=ans.end();it++)            if(it->first==num)            {                it->second++;                flag=1;            }        if(!flag)            ans.insert(make_pair(num,1));    }    for(int i=0;i<len_s2;i++)    {        if(!islower(s2[i]))            s2[i]=tolower(s2[i]);        int num=s2[i];        map<int,int>::iterator it;        int flag=0;        for(it=bns.begin();it!=bns.end();it++)            if(it->first==num)            {                it->second++;                flag=1;            }        if(!flag)            bns.insert(make_pair(num,1));    }    map<int,int>::iterator it1,it2;    it1=ans.begin();    while(it1!=ans.end())    {        int flag=0;        for(it2=bns.begin();it2!=bns.end();it2++)            if(it2->first==it1->first&&it2->second==it1->second)                flag=1;        if(!flag)        {            printf("N/n");            return 0;        }        it1++;    }    printf("Y/n");    return 0;}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表