Ananagrams(反片語)【map的應用】P114
阿新 • • 發佈:2018-03-24
ram i++ name 返回 dealer 文本 des cme 叠代
中文題意:輸入一些單詞,找出滿足如下條件的單詞:該單詞不能通過字母重排,得到文本中的另一個單詞。
在判斷是否滿足條件時,字母不分大小寫,
但在輸出是應保留輸入中的大小寫,按字典序進行排序(所有大寫字母在所有小寫字母的前面)。
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 #
#include<bits/stdc++.h> using namespace std; map<string,int>cnt; vector<string>words; //將單詞s進行“標準化” string repr(const string &s) { string ans=s; for(int i=0;i<ans.length();i++) { ans[i]=towlower(ans[i]);//把所有字母變為小寫字母,方便統計 } sort(ans.begin(),ans.end()); return ans; } int main() { int n=0; strings; 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]<<endl; } return 0; }
map和set兩種容器的底層結構都是紅黑樹,所以容器中不會出現相同的元素,因此count()的結果只能為0和1,可以以此來判斷鍵值元素是否存在(當然也可以使用find()方法判斷鍵值是否存在)。
拿map<key,value>舉例,find()方法返回值是一個叠代器,成功返回叠代器指向要查找的元素,失敗返回的叠代器指向end。count()方法返回值是一個整數,1表示有這個元素,0表示沒有這個元素。
Ananagrams(反片語)【map的應用】P114