题目大意:
输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排,得到输入文本中的另外一个单词。在判断是否满足条件时,字母不分大小写,但在输出时应保留输入中的大小写,按字典序排列。
题目(提交)链接→UVa-156
没使用过该网站的同学请猛戳这里→vJudge教程
储备知识:
1、标准化:
将一个字符串中所有字母化简为小写,并按其字典序排列的过程叫标准化。
2、map的基本用法→map头文件函数详解
3、tolower函数出处→ctype头文件函数详解
4、sort、count函数出处→algorithm头文件函数详解
分析:
此题大水题,想要做出来不难,但如果想找到最优解,难度就上升一个档次了。尤其是map+vector配合标准化的写法,以及最后以空间换时间的思想,都是值得借鉴和学习的。
思路:
vector1存放输入串,将每个串的标准化存入map.key,出现次数存入map.value;输入结束后遍历vector1与map1,若vector1中串出现次数等于1,就存入vector2串。 最后给vector2串排序,输出。
代码:
#include <bits/stdc++.h>
using namespace std;
map<string,int> cnt;
vector<string> words;
//将单词s进行“标准化”
string repr(const string& s) { //传递参数时加const可以避免参数被意外修改
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]++;
}
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] << "\n";
return 0;
}
收获:
1、map映射的用法
2、标准化的用法