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

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

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

一次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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值