1. 程式人生 > 實用技巧 >【C/C++】例題5-4 反片語/演算法競賽入門經典/C++與STL入門/對映:map

【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");
}