UVA - 156 Ananagrams

Most crossword puzzle fans are used to anagrams — groups of words with the same letters in different orders — for example OPTS, SPOT, STOP, POTS and POST. Some words however do not have this attribute, no matter how you rearrange their letters, you cannot form another word. Such words are called ananagrams, an example is QUIZ. Obviously such definitions depend on the domain within which we are working; you might think that ATHENE is an ananagram, whereas any chemist would quickly produce ETHANE. One possible domain would be the entire English language, but this could lead to some problems. One could restrict the domain to, say, Music, in which case SCALE becomes a relative ananagram (LACES is not in the same domain) but NOTE is not since it can produce TONE. Write a program that will read in the dictionary of a restricted domain and determine the relative ananagrams. Note that single letter words are, ipso facto, relative ananagrams since they cannot be “rearranged” at all. The dictionary will contain no more than 1000 words. Input Input will consist of a series of lines. No line will be more than 80 characters long, but may contain any number of words. Words consist of up to 20 upper and/or lower case letters, and will not be broken across lines. Spaces may appear freely around words, and at least one space separates multiple words on the same line. Note that words that contain the same letters but of differing case are considered to be anagrams of each other, thus ‘tIeD’ and ‘EdiT’ are anagrams. The file will be terminated by a line consisting of a single ‘#’. Output Outputwillconsistofaseriesoflines. Eachlinewillconsistofasinglewordthatisarelativeananagram intheinputdictionary. Wordsmustbeoutputinlexicographic(case-sensitive)order. Therewillalways be at least one relative ananagram.


题目大意:若一个单词可通过改变字母顺序得到另一个单词,则称这两个单词是一样的。现给出一个文本,要求找出所有通过改变字母顺序不能得到该文本中其他单词的所有单词,并按字典序输出(注:输出时按原单词输出)

思路:map统计单词个数,set排序单词。

1.判断单词是否一样:将单词都转为小写字母,并按字典序排序,则该单词即为我们所定义的“标准单词”,map中的键值是“标准单词”,映射是单词个数。

2.输出单词:读入单词的同时将单词加入set,因为set自身的排序功能,所以输出时只需遍历一遍set,如果set当前单词在文本中仅有一个,则输出这个单词。

代码如下:

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

string lw(string &s)
{
	int i;string ss;
	ss=s;
	for (i=0;i<ss.length();i++)
	  ss[i]=tolower(ss[i]);
	sort(ss.begin(),ss.end());
	return ss;
}

int main()
{
	string s,s2;
	map<string,int> m;
	set<string> words;
	int i;
	m.clear();
	while (cin>>s)
	{
		if (s=="#") break;
		s2=lw(s);
		words.insert(s);
		m[lw(s)]++;
	}
    set<string>::iterator it;
	for (it=words.begin();it!=words.end();it++)
	{
	  s2=*it;
	  if (m[lw(s2)]==1) cout<<*it<<endl;
    }
	return 0;	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值