反片語(Ananagrams,Uva 156)
輸入一些單詞,找出所有滿足如下條件的單詞:該單詞不能通過字母重排,得到輸入文 本中的另外一個單詞。在判斷是否滿足條件時,字母不分大小寫,但在輸出時應保留輸入中 的大小寫,按字典序進行排列(所有大寫字母在所有小寫字母的前面)。
樣例輸入:
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 #
樣例輸出:
Disk
NotE
derail
drIed
eye
ladder
soon
【分析】 把每個單詞“標準化”,即全部轉化為小寫字母后再進行排序,然后再放到map中進行統(tǒng) 計。代碼如下:
#include<iostream> #include<string> #include<cctype> #include<vector> #include<map> #include<algorithm> using namespace std; map<string ,int> cnt; vector<string> words; 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); 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; }
此例說明,如果沒有良好的代碼設計,是無法發(fā)揮STL的威力的。如果沒有想到“標準 化”這個思路,就很難用map簡化代碼。
map就是從鍵(key)到值(value)的映射。因為重載了[ ]運算符,map像是數(shù)組的“高 級版”。例如可以用一個map<string,int>month_name來表示“月份名字到月份編號”的映射, 然后用month_name["July"]=7這樣的方式來賦值。
set頭文件中的set和map頭文件中的map分別是集合與映射。二者都支持 insert、find、count和remove操作,并且可以按照從小到大的順序循環(huán)遍歷其中的元素。 map還提供了“[]”運算符,使得map可以像數(shù)組一樣使用。事實上,map也稱為“關聯(lián)數(shù) 組”。
注:
使用count,返回的是被查找元素的個數(shù)。如果有,返回1;否則,返回0。注意,map中不存在相同元素,所以返回值只能是1或0。
使用find,返回的是被查找元素的位置,沒有則返回map.end()。

浙公網(wǎng)安備 33010602011771號