《编程珠玑》代码之路4:变位词集合完整代码

字典的变位词集合:变位词就是由相同的字母的不同顺序组成的单词,例如pots和stop就是变位词,按构成字母顺序排序的opst就是他两的标志。

现在给一个字典,把变位词一起输出:

例如一个字典:

pans
pots
opt
snap
stop
tops

那么对应的标志分别是:

anps pans
opst pots
opt opt
anps snap
opst stop
opst tops

最后输出:

anps: pans snap 
opst: pots stop tops 
opt: opt 

#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

class Word{
public:
	string word;//单词
	string sign;//标志

	Word(){
		word = "";
		sign = "";
	}

	bool operator < (const Word &b) const {
		return sign < b.sign;
	}
}dict[10000];

int nWord = 0;

//读取数据
int readData(Word dict[]);
//计算每个单词的标志sign
int Sign(Word dict[]);
//按标志sign给字典排序
int Sort(Word dict[]);
//按照标志输出单词
int Squash(Word dict[]);

int main(){
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);

	readData(dict);
	Sign(dict);
	Sort(dict);
	Squash(dict);

	return 0;
}

int readData(Word dict[]){
	char word[100];
	
	while (scanf("%s", &word) != EOF){
		dict[nWord].word = dict[nWord].sign = word;
		cout << dict[nWord].word << endl;
		nWord++;
	}
	return 0;
}

int Sign(Word dict[]){

	freopen("sign.txt", "w", stdout);
	for (int i = 0; i < nWord; ++i){
		sort(dict[i].sign.begin(), dict[i].sign.end());
		cout << dict[i].sign << ' ' << dict[i].word << endl;
	}
	return 0;
}

int Sort(Word dict[]){
	freopen("sort.txt", "w", stdout);
	sort(dict, dict + nWord);

	for (int i = 0; i < nWord; ++i){
		cout << dict[i].sign << ' ' << dict[i].word << endl;
	}
	return 0;
}

int Squash(Word dict[]){
	freopen("out.txt", "w", stdout);

	string oldSign = "";
	int curWord = 0;

	cout << dict[0].sign << ": ";
	for (int i = 0; i < nWord; ++i){
		if (oldSign != dict[i].sign && curWord > 0){
			cout << endl;
			cout << dict[i].sign << ": ";
		}

		curWord++;
		oldSign = dict[i].sign;
		cout << dict[i].word << ' ';
	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/beijixiong5622/article/details/84073033