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

来源:互联网 发布:一键抠图软件怎么清理 编辑:程序博客网 时间:2024/06/04 23:30

 题目大意:

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

实现1:(用数组模拟)

#include<set>#include<iostream>#include<map>#include<algorithm>#include<cstring> #define maxn 1000using 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());