算法入门经典-第五章 例题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; 
}

  

转载于:https://www.cnblogs.com/is-Tina/p/7350507.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值