(C++)反片语

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LL596214569/article/details/83832622

题目:

输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排,得到输入文本中的另外一个单词。
在判断是否满足条件时,字母不分大小写,但在输入时应保留输入中的大小写,按字典序进行排列(所有大写字母在小写字母的前面)
样例输入:
ladder came tape soon leader acme RIDE lone Dreis peat
ScAlE orb eye Rides dealer NotE derail LaCeS drIed
noel dire Disk mace Rob dries
样例输出:
Disk
NotE
derail
drIed
eye
ladder
soon
这一题目是偶然从柳婼小姐姐的博客上看到的,看到之后觉得很有意思,然后试着写了一下,虽然勉强写了出来,但是看了柳婼小姐姐写的答案之后自愧不如。。我用的方法太繁琐了,这里先将柳婼小姐姐的答案贴上,等我在改进一下我的答案再酌情贴不贴。。。原博传送门:https://blog.csdn.net/liuchuo/article/details/52014892

#include "stdafx.h"
#include <iostream>
#include <map>
#include <set>
#include <algorithm>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
map<string, int> mapp;
vector<string> words;

//将单词s标准化
string standard(const string &s) {
	string t = s;
	for (int i = 0; i < t.length(); i++) {
		t[i] = tolower(t[i]);
	}
	sort(t.begin(), t.end());
	return t;
}

int main() {
	string s;
	while (cin >> s) {
		if (s[0] == '#')
			break;
		words.push_back(s);
		string r = standard(s);
		if (!mapp.count(r))
			mapp[r] = 0;
		mapp[r]++;
	}

	vector<string> ans;
	for (int i = 0; i < words.size(); i++) {
		if (mapp[standard(words[i])] == 1)
			ans.push_back(words[i]);
	}
	sort(ans.begin(), ans.end());
	for (int i = 0; i < ans.size(); i++) {
		cout << ans[i] << endl;
	}

	system("pause");
}

猜你喜欢

转载自blog.csdn.net/LL596214569/article/details/83832622