(STL,map)反片语

题目

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

样例输入:

ladder came tape soon leader acme RIDE lone Dreis peat

ScALE orb eye Rides dealer NotE derail LaCeS drIed

noel dire Disk mace Rob dires

#

样例输出:

Disk
NotE
derail
drIed
eye
ladder
soon

分析与解答

1.单词标准化
标准化方式:全转化成小写字母之后再进行排序
如果一个单词经重排后能得到输入文本中另外一个单词,那经标准化后这单词有多个
2.利用map存标准化后的单词
每一个标准化的单词为key,个数为value,用map存起来
3.用words存初始单词
4.用ans存满足答案的单词
具体判断方法:word中单词在map中标准化对应的value为1
5.输出ans
自动由小到大输出

需要了解的:
vector< string> a;
sort(a.begin(),a.end())多个单词排序
string a=s;
sort(a.begin(),a.end())一个单词排序
map中count() 返回指定元素出现的次数

#include <map>
#include <vector>
#include <cctype>
#include <string>
#include <iostream>
#include <algorithm>
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);
        //count() 判断是否有元素 
        if(!cnt.count(r)) cnt[r] = 0;
        cnt[r]++;//单词计数 
    }
    vector<string> ans;
    for(int i = 0; i < words.size(); i++) {
        if(cnt[repr(words[i])] == 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/qq_40828914/article/details/81115072