Problem D Ananagrams(map的使用)

题目链接:Problem D

题意:输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排,得到输入文本中的另一个单词。在判断是否满足条件时,字母不区分大小写。

但是输出时应保留原始大小写,按字典序进行排列。

思路:把单词统一处理一下,然后放入map中,用vector记录下满足要求的单词,最后排序一下即可。

code:

 1 #include <iostream>
 2 #include <string>
 3 #include <map>
 4 #include <vector>
 5 #include <algorithm>
 6 #include <cctype>
 7 using namespace std;
 8 
 9 vector<string> words;
10 map<string, int> cnt;
11 
12 string repr(string str)
13 {
14     string ret = str;
15     int len = ret.size();
16     for (int i = 0; i < len; ++i)
17         ret[i] = tolower(ret[i]);
18     sort(ret.begin(), ret.end());
19     return ret;
20 }
21 
22 int main()
23 {
24     string str;
25     while (cin >> str)
26     {
27         if ('#' == str[0]) break;
28         words.push_back(str);
29         string t = repr(str);
30         if (cnt.count(t) == 0) cnt[t] = 0;
31         ++cnt[t];
32     }
33     int len = words.size();
34     vector<string> ans;
35     for (int i = 0; i < len; ++i)
36     {
37         if (1 == cnt[repr(words[i])])
38             ans.push_back(words[i]);
39     }
40     len = ans.size();
41     sort(ans.begin(), ans.end());
42     for (int i = 0; i < len; ++i)
43         cout << ans[i] << endl;
44     return 0;
45 }

 

posted @ 2015-06-30 15:57  jasaiq  阅读(348)  评论(0编辑  收藏  举报