您的位置:首页 > 其它

POJ1035——spell checker

2015-04-10 17:30 176 查看
正好最近被人问到一个数据结构的问题,难住了。所以决定来刷刷数据结构的题,从初级的开始,当回炉再造了。

题目大概意思:

作为一个拼写的checker,遵从如下几个规则——

(1)对待检查单词,删除一个字母后,能在字典中找到;

(2)对待检查单词,替换一个字母(任意字母替换)后,能在字典中找到;

(3)对待检查单词,插入一个任意字母后,能在字典中找到;

INPUT:

第一部分是字典,字典最多10000各单词,字典输入结束以‘#’号结束,每个单词占据一行

第二部分是要检查的单词,最多50个,也以’#‘号结束

每个单词最多15个字母构成

OUTPUT:

找到一样的,直接输出该单词+“is correct”

没找到的话,输出该单词+“:”+字典中相似的单词

这道题我WA了很多次,一开始始终没想通替换,删除,插入的核心,当时还想真在26的字母中找一个插入,然后进行匹配呢。犯2了!

我AC的思路是这样的:

把字典,和待检查的单词都放到数组里去[10001][16],[51][16];

对规则用3个函数来写;

不管删除还是其他操作,都只能对1个字母,所以只要找待检查单词和字典中单词大小的绝对值<=1的,然后进行规则操作;

对每一个待检查单词,都遍历一遍字典(很暴力);

#include<iostream>
#include<string>
using namespace std;

char dict[10001][16];
char wdchk[51][16];
int count_dict = 0;//字典计数器
int count_wdchk = 0;//待检查单次计数器

/*删除待检查单次中一个字母*/
bool del(char *wd, char *dict)
{
int dif = 0;//计数器,当前不同字符多少个
while (*wd)
{
if (*wd != *dict)
{
wd++;
dif++;
if (dif > 1)return false;
}
else
{
wd++;
dict++;
}
}
return true;
}

/*在待检查单词中插入一个字母*/
bool append(char *wd, char *dict)
{
int dif = 0;
while (*dict)
{
if (*wd != *dict)
{
dict++;
dif++;
if (dif > 1)return false;
}
else
{
dict++;
wd++;
}
}
return true;
}

/*对待检查单词替换任意一个字母*/
bool replace(char *wd, char *dict)
{
int dif = 0;
while (*wd)
{
if (*wd != *dict)
{
wd++;
dict++;
dif++;
if (dif > 1)return false;
}
else
{
wd++;
dict++;
}
}
return true;
}

int main(void){

while (cin >> dict[count_dict] && dict[count_dict++][0] != '#');
while (cin >> wdchk[count_wdchk] && wdchk[count_wdchk++][0] != '#');
count_dict--;//去除‘#’
count_wdchk--;
//输入结束测试
/*cout << count_dict << ' ' << count_wdchk << endl;
int temp = count_wdchk;
while (temp--)
{
cout << wdchk[temp] << endl;
}
*/
int* DictLen = new int[count_dict];  //记录计算字典中各个单词的长度
for (int n = 0; n<count_dict; n++)
DictLen
= strlen(dict
);

/*for (int c = 0; c < sizeof(DictLen); c++)
cout<< DictLen[c] << " ";*/

for (int i = 0; i < count_wdchk; i++)
{
int lenwd = strlen(wdchk[i]);
int *address = new int[count_dict];
int position=0;//待输出字典的位置
bool flag = false;//标记字典里是否有wdchk[i]
for (int j = 0; j < count_dict; j++)//遍历字典
{
if (lenwd==DictLen[j])
{
if (!strcmp(wdchk[i], dict[j]))
{
flag = true;
break;
}
else if (replace(wdchk[i], dict[j]))
{
address[position++] = j;
}
}
else if (lenwd - DictLen[j] == 1)
{
if (del(wdchk[i], dict[j]))
address[position++] = j;
}
else if (DictLen[j] - lenwd == 1)
{
if (append(wdchk[i], dict[j]))
address[position++] = j;
}
}
//output
if (flag)
cout << wdchk[i] << " is corrent" << endl;
else
{
cout << wdchk[i] << ":";
for (int k = 0; k < position; k++)
cout <<' '<< dict[address[k]];
cout << endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: