156 - Ananagrams

本文介绍了一个使用C++编写的程序,该程序能够读取一行包含多个单词的输入,并通过归并排序算法对这些单词进行排序,最终输出没有重复的单词。程序首先将所有单词转换为小写并重新排列字符以形成统一的标准形式,然后进行排序以找出唯一的单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstdio>
#include <string>
#include <cctype>
#include <sstream>
#include <algorithm>

using namespace std;
const int maxn=85;

struct Words
{
	string changedWord;
	string word;
}words[maxn*maxn];
string anagrams[maxn*maxn];

void change(int m)
{
	words[m].changedWord="";
	for(int i=0;i<words[m].word.size();i++)
	{
		words[m].changedWord+=tolower(words[m].word[i]);
	}
	sort(words[m].changedWord.begin(),words[m].changedWord.end());
}

bool cmp_words(const Words &a,const Words &b)
	//	Compilation error
	//sort中比较函数定义时,传入的参数必须为const常量
{
	return a.changedWord<b.changedWord;
}

int main()
{
	/*
	freopen("156.in","r",stdin);
	freopen("156.out","w",stdout);
	*/
	string line;
	int u=0;
	while(getline(cin,line))
	{
		if(line=="#")
			break;
		istringstream sin(line);
		string a;
		while(sin>>a)
		{
			words[u].word=a;
			change(u);
			u++;
		}
	}
	sort(words,words+u,cmp_words);
	int num=1;
	int v=0;
	for(int i=0;i<u;i++)
	{
		if(words[i].changedWord==words[i+1].changedWord)
			num++;
		else
		{
			if(num==1)
			{
				anagrams[v++]=words[i].word;
			}
			else
				num=1;
		}
	}
	sort(anagrams,anagrams+v);
	for(int i=0;i<v;i++)
		cout<<anagrams[i]<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值