UVA 156 Ananagrams 反片语

题目描述

输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排,得到输入文本中的另外一个单词。在判断是否满足条件时,字母不分大小写,但在输出时应该保留输入中的大小写,按字典序排列。

样例输入

ladder came tape soon leader acme RIDE lone Dreis peat
ScAlE orb eye Rides dealer NotE derail LaCeS drIed
noel dire Disk mace Rob dries #

样例输出

Disk
NotE
derail
drIed
eye
ladder
soon

题解

把每个单词“标准化”,再放入map中进行统计

CODE

#include <iostream>
#include <algorithm>
#include <map>
#include <cctype>
#include <vector>
#include <cstring>
using namespace std;
map<string,int> cnt; //存放标准化的字符串
vector<string> words; //存放输入的字符串
string repr(const string& s)
{
    string ans = s;
    for(int i=0; i<ans.length(); i++)
        ans[i] = tolower(ans[i]);
    sort(ans.begin(),ans.end());
    return ans;
}
int main()
{
    int n = 0;
    string s;
    while(cin >> s)
    {
        if(s[0] == '#')
            break;
        words.push_back(s);
        string r = repr(s);
        if(!cnt.count(r))//如果cnt中有r则返回0
            cnt[r] = 0;//说明可以由其他字符串转化而来
        cnt[r]++;
    }

    vector<string> ans;
    for(int i = 0; i < words.size(); i++)
        if(cnt[repr(words[i])] == 1)//如果值为1则说明这个字符串是唯一的
            ans.push_back(words[i]);
    sort(ans.begin(), ans.end());
    for(int i=0; i<ans.size(); i++)
        cout << ans[i] << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/AC__GO/article/details/81193164