算法入門經典 第五章
阿新 • • 發佈:2017-08-12
標準 name vector容器 兩個 clas 條件 tap 算法入門經典 字典
例題5-4 反片語
輸入一些單詞(以“#”為結束標誌),找出所有滿足如下條件的單詞:該單詞不能通過字母的重排,得到輸入文本中的另一個單詞。在判斷是否滿足條件是不分大小寫,但是在輸出時應保留輸入時的大小寫,按字典序進行排列(所有大寫字母在所有小寫字母前面)。
Sample input
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 #
Sample output
Disk NotE derail drIed eye ladder soon
分析
這道題的解法很多,最簡化的方式就是使用map容器。想到使用“標準化”。
整體思路:
1.寫一個標準化函數(實現大寫字母轉換為小寫(tolower()函數),單詞排序。註意使用const是為了不改變s的初值)
2.兩個vector容器(words,ans),一個map容器(cnt)
words存儲所有的單詞
map存儲標準化後對應單詞以及出現次數的值,相當於一個表格。
words經過查表map,把對應的符合值給ans
3.輸出
代碼:
#include<iostream> #include<string> #include<vector> #include<algorithm> #include<cctype> #include<map> 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.size();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); //cout<<r<<endl; if(!cnt.count(r))cnt[r]=0;//count()如果鍵值存在返回1,否則返回0;初始化鍵值對應的值 cnt[r]++;//計算出現的次數 類似數組的初始化 沒出現過所以先初始化0 出現過map鍵值對應的count++ } vector<string>ans; for(int i=0;i<words.size();i++) if(cnt[repr(words[i])]==1)ans.push_back(words[i]);//查map表,將符合條件的單詞放進ans容器 sort(ans.begin(),ans.end()); for(int i=0;i<ans.size();i++) cout<<ans[i]<<endl; return 0; }
算法入門經典 第五章