您的位置:首页 > 其它

POJ1035《Spell checker》方法:模拟

2013-03-16 16:59 197 查看
就是辨别单词和字典中相等或多一个字母或少一个字母的情况。

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

char dict[10001][16];
char word[51][16];

int dictnum = 0;
int wordnum = 0;

bool change(char *s, char *t)
{
	int dif = 0;
	while (*s) {
		if (*s++ != *t++) {
			++dif;
			if (dif > 1) //有一个以上不同就返回false
				return false;
		}
	}
	return true;
}

bool del(char *s, char *t)
{
	int dif = 0;
	while (*s) {
		if (*s != *t) {
			++s;
			++dif;
			if (dif > 1)
				return false;
		} else {
			++s;
			++t;
		}
	}
	return true;
}

bool add(char *s, char *t)
{
	int dif = 0;
	while (*s) {
		if (*s != *t) {
			++t;
			++dif;
			if (dif > 1)
				return false;
		} else {
			++s;
			++t;
		}
	}
	return true;
}

int main()
{
	//freopen("temp.txt", "r", stdin);
	//读入数据
	while (cin >> dict[dictnum] && dict[dictnum++][0] != '#') 
		;
	--dictnum; //减去'#'
	while (cin >> word[wordnum] && word[wordnum++][0] != '#') 
		;
	--wordnum;

	//记录dict长度
	int *dictlen  = new int[dictnum];
	for (int i = 0; i < dictnum; ++i) {
		dictlen[i] = strlen(dict[i]);
	}

	//判定每一个word
	for (int i = 0; i < wordnum; ++i) {
		bool flag = false; //is correct
		int len = strlen(word[i]);

		int *address = new int[dictnum]; // 临时记录每个word的结果
		int pa = 0; //address指针

		for (int j = 0; j < dictnum; ++j) {
			if (len == dictlen[j]) { //第一层判断条件是长度相差一
				if (!strcmp(word[i], dict[j])) {
					flag = true;
					break;
				} else if (change(word[i], dict[j])) {
					address[pa++] = j;
				}
			} else if (len - dictlen[j] == 1) {
				if (del(word[i], dict[j]))
					address[pa++] = j;
			} else if (dictlen[j] - len == 1) {
				if (add(word[i], dict[j]))
					address[pa++] = j;
			}
		}
		if (flag) {
			cout << word[i] << " is correct" << endl;
		} else {
			cout << word[i] << ": ";
			for (int i = 0; i < pa; ++i)
				cout << dict[ address[i] ] << ' ';
			cout << endl;
		}
		delete address;
	}
	delete dictlen;
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: