【C/C++】例题5-4 反片语/算法竞赛入门经典/C++与STL入门/映射:map

本题是映射:map的例题。
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 dries #

【输出】

【思路】
将所有单词输入,转成小写字母,排序。然后放到map中进行统计。

【代码】

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <functional>
using namespace std;

vector<string> words;
map<string, int> cnt; //记录每一个string出现的次数

//将单词进行标准化
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); //用words存储所有的读入的string
      string r = repr(s); //用r存储标准化后的单词s
      int flag = cnt.count(r); //可能的结果:0或1
      if (flag == 0)
      {
         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";
   }

   system("pause");
}
posted @ 2020-11-25 21:10  KinoLogic  阅读(95)  评论(0编辑  收藏  举报