您的位置:首页 > 编程语言 > C语言/C++

poj1035 spell checker (简单的字符串查找题)

2015-08-16 00:25 471 查看
题意:给定字典里一堆单词,建立一系列询问,每个询问有一个单词,问在字典里存不存在这个单词的原型,或者字典里的词添加一个字母,删除一个字母,替换一个字母可以得到这个单词。

一个个模拟就好,注意字符串比较的题目,变量往往非常多,一定要保持思路清晰,不可急躁。

一次A。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <algorithm>
#include <cstring>
#include <utility>
#define ll long long
#define INF 0x3f3f3f3f

using namespace std;

char dic[10005][20];
int len[10005];
char ch[20],tt[20];
int tlen,num=0;
bool res,a;

bool _change(int x) //改变一个字母
{
int temp=0;
for(int i=0;i<tlen;i++)
{
if(ch[i]!=dic[x][i])
{
temp++; //依次比较每个字母
}
if(temp>1)
return false;
}
return true;
}

bool _delete(int x) //删除一个字母
{
int temp=0;
for(int i=0,j=0;i<tlen;i++,j++) //注意范围,保证最短的不会re
{
if(ch[i]!=dic[x][j])
{
temp++; //变量比较多,思路要保持清晰
i--; //下一轮中i保持不变
}
if(temp>1) return false;
}
return true;
}

bool _insert(int x) //添加一个字母
{
int temp=0;
for(int i=0,j=0;j<tlen-1;i++,j++) //同删除一样,只不过交换下对象
{
if(ch[i]!=dic[x][j])
{
temp++;
j--;
}
if(temp>1) return false;
}
return true;
}

int main()
{
while(1)
{
scanf("%s",tt);
if(strcmp(tt,"#")==0) break;
else
{
//printf("%s\n",tt);
strcpy(dic[num],tt);
len[num]=strlen(tt); //把每个单词的长度记录下来
//printf("%s %d\n",dic[num],len[num]);
num++; //记录字典内单词的个数(多了一个)
}
}

while(scanf("%s",ch)!=EOF)
{
if(strcmp(ch,"#")==0) break;
a=false;
tlen=strlen(ch);

for(int i=0;i<num;i++)
{
if(!strcmp(ch,dic[i]))
{
printf("%s is correct\n",ch); //这里要注意,因为如果有完全一样的,就不用再进行其他的操作了
a=true;
}
}

if(!a) //保证没有完全相同的
{
printf("%s:",ch);
for(int i=0;i<num;i++)
{
//printf("aa\n");
if(tlen==len[i])
{
res=false; //每次res都需要重置
res=_change(i);
if(res) printf(" %s",dic[i]);
}

if(tlen==len[i]-1)
{
res=false;
res=_delete(i);
if(res) printf(" %s",dic[i]);
}

if(tlen==len[i]+1)
{
res=false;
res=_insert(i);
if(res) printf(" %s",dic[i]);
}
}
printf("\n");
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm c++ 模拟 水题 poj