习题 5-4 反片语(Ananagrams)UVa 156

 题目大意:

输入一些单词,找出满足如下规则的单词:该单词不能通过字母重排,得到输入文本中的另外一个单词。判断时候字母不区分大小写,但是输出时候应该保留输入时候的大小写,并且按照字典序进行排序(大写字母排在小写字母前面)。

实现1:(用数组模拟)

#include<set>
#include<iostream>
#include<map>
#include<algorithm>
#include<cstring> 
#define maxn 1000
using namespace std;

struct Str{
	char low[100];//保存小写单词
	char str[100];//原单词
	bool flag;//标记是否满足条件
}s[maxn];
struct R{
	char s[100];
}r[maxn];//保存满足条件的单词
int cmp(R a, R b)
	{
		return strcmp(a.s, b.s) < 0;
	}
int main()
	{
	//	freopen("C:\\Users\\zhangwei\\Desktop\\input.txt","r",stdin);
		int count = 0;
		while(cin >> s[count].str){
			if(s[count].str[0] == '#')
				break;
			for(int i = 0; i < strlen(s[count].str); i++ ){
				s[count].low[i] = tolower(s[count].str[i]);
			}
			sort(s[count].low, s[count].low+strlen(s[count].str));//关键
			s[count].flag = true;
			count++;	
		}
		for(int i = 0; i < count; i++ ){//所有单词进行两两比较
			for(int j = i+1; j < count; j++ ){
				if(strcmp(s[i].low,s[j].low) == 0){
					s[i].flag = false;
					s[j].flag = false;
				}
			}
		}		
		int cnt = 0;		
		for(int i = 0; i < count ; i++ ){
			if(s[i].flag == true){//保存满足条件的单词
				strcpy(r[cnt++].s, s[i].str);
			}
		}
		sort(r, r+cnt, cmp);//按照字典序排序
		for(int i = 0; i < cnt; i++ ){
			cout << r[i].s <<endl;
		}
		
		return 0;
	}

实现2:(用map,vector)

#include<set>
#include<iostream>
#include<map>
#include<algorithm>
#include<cstring> 
#include<vector>
using namespace std;

string repr(const string &s)
	{
		string tmp = s;
		for(int i = 0; i < s.length(); i++ ){
			tmp[i] = tolower(s[i]);
		}
		sort(tmp.begin(),tmp.end());//关键
		return tmp;
	}
vector<string> words;
map<string,int> cnt;//键值对
int main()
	{
	//	freopen("C:\\Users\\zhangwei\\Desktop\\input.txt","r",stdin);
		string s;
		string tmp;
		while(cin >> s){
			if(s[0] == '#')
				break;
			words.push_back(s);
			tmp = repr(s);
			++cnt[tmp];
		} 
		vector<string> ans;
		for(int i = 0; i < words.size(); i++ ){
			if(cnt[repr(words[i])] == 1){
				ans.push_back(words[i]);
			}
		}
		vector<string>::iterator it;
		sort(ans.begin(),ans.end());//默认字典序
		for(it = ans.begin(); it != ans.end(); it++ ){
			cout << *it <<endl;
		}
		
		return 0;
	}

注意:(2)中用到了sort 对 string 类型数据进行排序 还有 对string 数据内部的字符串进行排序

                    不同于普通字符串sort(a,a+n)  而是sort(a.begin(), a.end());

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值