poj1035 Spell Checker

題目:

1:拼寫檢查
查看 提交 統計 提問
總時間限制: 2000ms 內存限制: 65536kB
描述
現在有一些英語單詞需要做拼寫檢查,你的工具是一本詞典。需要檢查的單詞,有的是詞典中的單詞,有的與詞典中的單詞相似,你的任務是發現這兩種情況。單詞A與單詞B相似的情況有三種:
1、刪除單詞A的一個字母后得到單詞B;
2、用任意一個字母替換單詞A的一個字母后得到單詞B;
3、在單詞A的任意位置增加一個字母后得到單詞B。
你的任務是發現詞典中與給定單詞相同或相似的單詞。


輸入
第一部分是詞典中的單詞,從第一行開始每行一個單詞,以"#"結束。詞典中的單詞保證不重複,最多有10000個。
第二部分是需要查詢的單詞,每行一個,以"#"結束。最多有50個需要查詢的單詞。
詞典中的單詞和需要查詢的單詞均由小寫字母組成,最多包含15個字符。
輸出
按照輸入的順序,爲每個需要檢查的單詞輸出一行。如果需要檢查的單詞出現在詞典中,輸出“?x is correct",?x代表需要檢查的單詞。如果需要檢查的單詞沒有出現在詞典中,則輸出"?x: ?x1 ?x2 ...?xn",其中?x代表需要檢查的單詞,?x1...?xn代表詞典中與需要檢查的單詞相似的單詞,這些單詞中間以空格隔開。如果沒有相似的單詞,輸出"?x:"即可。

樣例輸入
i
is
has
have
be
my
more
contest
me
too
if
award
#
me
aware
m
contest
hav
oo
or
i
fi
mre
#

樣例輸出
me is correct
aware: award
m: i my me
contest is correct
hav: has have
oo: too
or:
i is correct
fi: i
mre: more me


======================================================================

Brute force...


代碼清單:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
using namespace std;

#define MAXLEN 16
#define MAXENTRY 10005

char dict[MAXENTRY][MAXLEN];

bool isValid(int ind, char inq[])
{
	int len1=strlen(dict[ind]);
	int len2=strlen(inq);
	int same=0, i, j;

	if (len1==len2)
	{
		for (i=0; i<len1; ++i)
		{
			if (dict[ind][i]==inq[i])
			{
				++same;
			}
		}
		if(same==len1-1)
			return true;
	}
	else if (len1==len2-1)	//待查單詞比字典單詞多一個字母
	{
		for (i=0, j=0; i<len1&&j<len2;)
		{
			if (dict[ind][i]==inq[j])
			{
				++same;
				++i;
				++j;
			}
			else
				++j;
		}
		if (same==len1)
			return true;
	}
	else if (len1==len2+1)	//待查單詞比字典單詞少一個字母
	{
		for (i=0, j=0; i<len1&&j<len2;)
		{
			if (dict[ind][i]==inq[j])
			{
				++same;
				++i;
				++j;
			}
			else
				++i;
		}
		if (same==len2)
			return true;
	}

	return false;
}

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

	char current[MAXLEN];
	int entryNum=0;
	bool directHit;

	while (1)
	{
		scanf("%s", dict[entryNum]);
		if (dict[entryNum][0]=='#') break;
		++entryNum;
	}

	while (1)
	{
		scanf("%s", current);

		if(current[0]=='#') break;

		directHit=false;
		
		//直接能在字典中找到
		for (int i=0; i<entryNum; ++i)
		{
			if (strcmp(dict[i], current)==0)
			{
				printf("%s is correct\n", current);
				directHit=true;
				break;
			}
		}

		//以下是需要操作的情況
		if (!directHit)
		{
			printf("%s:", current);

			for (int i=0; i<entryNum; ++i)
			{
				if (isValid(i, current))
				{
					printf(" %s", dict[i]);
				}
			}

			printf("\n");
		}
	}

	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章