|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include <bits/stdc++.h>
- using namespace std;
- // 先将单词初始化,变成小写,然后进行排序
- string repr(const string &s)
- {
- string ans=s;
- for(int i=0;i<ans.size();i++)
- {
- ans[i]=tolower(ans[i]);
- }
- sort(ans.begin(),ans.end());
- return ans;
- }
- int main()
- {
- int n=0;
- string s;
- vector<string>words;
- map<string,int> cnt;
- while(cin>>s)
- {
- if(s[0]='#')break;
- words.push_back(s); //保留原来的字符串
- string t=repr(s);
- if(!cnt.count(t))cnt[t]=0;//如果没有查找到了,将其默认为0
- //跟Python的字典一样,键是唯一的,count是查找键的个数,由于键只存在一个,所以最大也只能为1
- cnt[t]++;
- }
- vector<string> a;
- for(int i=0;i<words.size();i++)
- {
- if(cnt[repr(words[i])]==1) a.push_back(words[i]);
- }
- sort(a.begin(),a.end());//还要排序
- for(auto i:a)
- {
- cout<<i<<endl;
- }
- }
复制代码
紫书上的一道题目
以下是修改过的代码:
- #include <iostream>
- #include <vector>
- #include <map>
- #include <algorithm>
- using namespace std;
- // 先将单词初始化,变成小写,然后进行排序
- string repr(const string& s) {
- string ans = s;
- for (int i = 0; i < ans.size(); i++) {
- ans[i] = tolower(ans[i]);
- }
- sort(ans.begin(), ans.end());
- return ans;
- }
- int main() {
- int n = 0;
- string s;
- vector<string> words;
- map<string, int> cnt;
- while (cin >> s) {
- if (s[0] == '#')
- break;
- words.push_back(s); // 保留原来的字符串
- string t = repr(s);
- if (!cnt.count(t))
- cnt[t] = 0; // 如果没有查找到了,将其默认为0
- cnt[t]++;
- }
- vector<string> a;
- for (int i = 0; i < words.size(); i++) {
- if (cnt[repr(words[i])] == 1)
- a.push_back(words[i]);
- }
- sort(a.begin(), a.end()); // 还要排序
- for (auto i : a) {
- cout << i << endl;
- }
- return 0;
- }
复制代码
这个程序的功能是从标准输入中读取单词,并按照一定规则进行处理和排序后输出。它使用了 vector存储单词,使用 map来统计每个单词的出现次数,使用 sort函数对结果进行排序。
希望这个回答对你有帮助。如果还有其他问题,请随时提问。
球一个最佳答案谢谢啦!这对我非常重要!  
|
|