poj 1035 Spell checker(hash)

时间:2022-07-28 16:57:12

题目链接http://poj.org/problem?id=1035

思路分析

1、使用哈希表存储字典

2、对待查找的word在字典中查找,查找成功输出查找成功信息

3、若查找不成功,对word增、删、改处理,然后在字典中查询,若查找成功则记录处理后单词在字典中的次序

4、对次序排序再输出

注:对word处理后可能会出现重复,需要进行判断重

代码如下:

#include <iostream>
using namespace std; const int N = ;
const int tSize = ;
char hashDic[tSize][N];
int stateDic[tSize];
int rankDic[tSize]; char words[tSize][N];
int stateW[tSize]; int Ans[tSize];
int ansLen; int InsertDic( char *key, int pos )
{
int len = strlen( key );
unsigned int hashVal = ; for ( int i = ; i < len; ++i )
hashVal = ( hashVal * + key[i] - 'a' ) % tSize; while ( stateDic[hashVal] != &&
strcmp( hashDic[hashVal], key ) != )
{
hashVal = ( hashVal + ) % tSize;
} if ( stateDic[hashVal] == )
{
stateDic[hashVal] = ;
strcpy( hashDic[hashVal], key );
rankDic[hashVal] = pos;
return true;
} return false;
} int InsertWords( char *key )
{
int len = strlen( key );
unsigned int hashVal = ; for ( int i = ; i < len; ++i )
hashVal = ( hashVal * + key[i] - 'a' ) % tSize; while ( stateW[hashVal] !=
&& strcmp( words[hashVal], key ) != )
{
hashVal = ( hashVal + ) % tSize;
} if ( stateW[hashVal] == )
{
stateW[hashVal] = ;
strcpy( words[hashVal], key );
return true;
} return false;
} int Find( char *key )
{
int len = strlen( key );
unsigned int hashVal = ; for ( int i = ; i < len; ++i )
hashVal = ( hashVal * + key[i] - 'a' ) % tSize; while ( stateDic[hashVal] != &&
strcmp( hashDic[hashVal], key ) != )
{
hashVal = ( hashVal + ) % tSize;
} if ( stateDic[hashVal] == )
return -;
else
return hashVal;
} int cmp( const void *a, const void *b )
{
int *pA = (int *)a;
int *pB = (int *)b; return rankDic[*pA] - rankDic[*pB];
} int main( )
{
int countDic = ;
char word[N]; memset( stateDic, , sizeof( stateDic ) );
while ( scanf( "%s", word ) == )
{
if ( word[] == '#' )
break; InsertDic( word, countDic++ );
} while ( scanf( "%s", word ) == )
{
char copy[N];
int indexWord;
int len = strlen( word ); if ( word[] == '#' )
break; ansLen = ;
memset( stateW, , sizeof( stateW ) );
printf( "%s", word ); indexWord = Find( word );
if ( indexWord > - )
{
printf( " is correct\n" );
continue;
} for ( int i = ; i <= len; ++i )
{
int j; strcpy( copy, word );
for ( j = len; j >= i; --j )
copy[j + ] = copy[j];
for ( char a = 'a'; a <= 'z'; ++a )
{
copy[i] = a; indexWord = Find( copy );
if ( indexWord > - && InsertWords( copy ) )
Ans[ansLen++] = indexWord;
}
} for ( int i = ; i < len; ++i )
{
strcpy( copy, word );
for ( int j = i + ; j <= len; ++j )
copy[j - ] = copy[j]; indexWord = Find( copy );
if ( indexWord > - && InsertWords( copy ) )
Ans[ansLen++] = indexWord;
} for ( int i = ; i < len; ++i )
{
strcpy( copy, word );
for ( char w = 'a'; w <= 'z'; ++w )
{
copy[i] = w; indexWord = Find( copy );
if ( indexWord > - && InsertWords( copy ) )
Ans[ansLen++] = indexWord;
}
} qsort( Ans, ansLen, sizeof( Ans[] ), cmp );
printf( ":" ); for ( int i = ; i < ansLen; ++i )
printf( " %s", hashDic[Ans[i]] );
printf( "\n" );
} return ;
}