算法入门经典-第五章 例题5-4 反片语

例题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; 
}

  

posted @ 2017-08-12 15:46  于繁华求淡然  阅读(390)  评论(0编辑  收藏  举报