【UVA】Ananagrams(map)

题目链接

PDF

英语硬伤,这个题意真是看得我头疼,大概意思就是找到全排列只在给出的单词表中出现过一次的单词。

补充:
string可以直接用sort排序,比如说升序排列:sort(str.begin(),str.end(),less);
vector也可以yongsort排序,和string类似:sort(vec.begin(),str.end(),cmp);

思路:

将字符串str其转换为小写字母,并将其按字典序升序排列的temp(sort,降序也可以,统一就行了),然后利用map,map[temp]++;并将str存在一个vector中。
将vector按字典升序排列,依次判断每个字符串str的小写升序是否只出现过一次,如果是的话,输出str。

超时代码:

#include <stdio.h>
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;

int main(void){
    map<string,int> m;
    map<string,int>::iterator it;
    string str,temp;
    vector<string> vec;
    while(cin>>str){
        vec.push_back(str);
        if(str=="#")    break;
        temp = str;
        for(int i=0;i<temp.size();++i)
            if(temp[i] >= 'A' && temp[i] <= 'Z')    temp[i] += 32;
        sort(temp.begin(),temp.end(),less<char>());     //string可以直接排序
        do  {
            m[temp]++;
        }while(next_permutation(temp.begin(),temp.end()));
    sort(vec.begin(),vec.end());
    for(int i=0;i<vec.size();++i){
        temp = vec[i];
        for(int j=0;j<temp.size();++j)
            if(temp[j] >= 'A' && temp[j] <= 'Z')    temp[j] += 32;
        if(m[temp] == 1)    cout<<vec[i]<<endl;
    }
    return 0;
}
/*
超时了,其实没有必要把所有的全排列全部统计,只用统计一个固定的格式的就可以了,比如我ac代码就用的小写升序格式。
在判断时将字符串都统一一下形式就好了。
每个单词最多二十个字母,全排列一下就是A(20,20),也就是20!次,不超时才怪。
*/

AC代码:

#include <stdio.h>
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;

int main(void){
    map<string,int> m;
    map<string,int>::iterator it;
    string str,temp;
    vector<string> vec;
    while(cin>>str){
        vec.push_back(str);
        if(str=="#")    break;
        temp = str;
        for(int i=0;i<temp.size();++i)
            if(temp[i] >= 'A' && temp[i] <= 'Z')    temp[i] += 32;
        sort(temp.begin(),temp.end(),less<char>());     //string可以直接排序
        m[temp]++;
//      cout<<temp<<endl;
    }
    sort(vec.begin(),vec.end());
    for(int i=0;i<vec.size();++i){
        temp = vec[i];
        for(int j=0;j<temp.size();++j)
            if(temp[j] >= 'A' && temp[j] <= 'Z')    temp[j] += 32;
        sort(temp.begin(),temp.end(),less<char>());     //string可以直接排序
        if(m[temp] == 1)    cout<<vec[i]<<endl;
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值