UVA - 156 - Ananagrams

8 篇文章 0 订阅

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=98&page=show_problem&problem=92


题意:

    背景,对于一个单词,如果字母乱序后(大小写有效)还是一个单词,那就称这个单词为anagram;否则为ananagram。

    输入字典(几行单词行),要求输出所有独特的ananagram(就是字母乱序后在输入行里不再出现)。要求输出时以字典顺序输出,即AaBbCc。


解题:

    对于一个单词,变化点有:顺序、大小写。都转换成小写+正序后,再来对比就简单了。

    输入的时候用istringstream分离出单词来;

    输入的同时,用vector保存原始单词(用于后续找回原始单词),用map保存处理后的单词(即小写化+正序化),同时可以用map记录最终单词的出现次数。

    处理时,只要把map里所有只出现一次的单词(即计数1次),在vector里把原始单词导出就行,保存到另外的map里(因为后续要以字典顺序输出)。

    最后输出最终map里的单词。


注意:

    中间经常要对string进行操作,涉及到复制的问题。要复制,而不能引用。


#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <string.h>
using namespace std;

// #define LOCAL_TEST

const int MAXN = 80;


int main()
{
#ifdef LOCAL_TEST
	freopen("f:\\in.txt", "r", stdin);
	freopen("f:\\out.txt", "w+", stdout);
#endif
	// use map(auto accending sort), mapLS→mapLowercaseSorted
	map<string, int> mapLS;
	// mapRes→mapResult, asked to print in dic'lexicographic order, use map
	map<string, int> mapRes;
	// vOri→vectorOriginal, used to save original strings
	vector<string> vOri;

	// using char* just 'cause have to use 'gets'
	char strIn[MAXN+1];
	while ( gets(strIn) )
	{
		if ( strIn[0] == '#' )
			break;

		// use istringstream to separate strings
		string strLine(strIn);
		istringstream strStream(strLine);
		string str;
		while ( strStream >> str )
		{
			// save to vector
			vOri.push_back(str);
			// use stl to set string lowercase, wonderful~
			transform(str.begin(), str.end(), str.begin(), ::tolower);
			sort(str.begin(), str.end());
			// count the lowercaseSorted strings
			if ( mapLS.count(str) )
				mapLS[str]++;
			else
				mapLS[str] = 1;
		} // end while
	} // end while

	// to get result/original string by lsString(one time)
	for ( map<string, int>::iterator it=mapLS.begin(); it!=mapLS.end(); it++ )
		// if lsString just appear one time
		if ( it->second == 1 )
			for ( vector<string>::iterator itV=vOri.begin(); itV!=vOri.end(); itV++ )
			{
				// to search original string in vOri
				string str(*itV);  // must copy string, not reference
				transform(str.begin(), str.end(), str.begin(), ::tolower);
				sort(str.begin(), str.end());
				// use mapRes to save result'string
				if ( it->first == str )
					mapRes[*itV] = 1;
			} // end for

	// print out, in lexicographic order
	for ( map<string, int>::iterator it=mapRes.begin(); it!=mapRes.end(); it++ )
		cout <<it->first <<'\n';

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值