哈希查找字符串

哈希查找的优越性:
当查找的字串长度小于机器字长时,可以把字串当做 long 进行比较。由于移位操作相当快(一个时钟周期),所以执行操作花费的时间比较少。
这种查找办法通用性不好。( big-endian or little-endian 问题)。但不可否认,它的查找速度确实快。

// "优快云" 的查找算法
// 思路是:把 "csdn" 按整数比较。每比较一次,对目标串进行移位操作。
void dwordsearch(const char pstr, const char* str )
{
    
const int* ptarget = (int*)str;
    
const int hash= *(int*)pstr;
    
// 出现的次数
    size_t index = 0;
    size_t index2 
= 0;
    vector
< size_t > posCollect;

    
//如果不是整数的倍数,保存尾巴和最后一个 int。
    int len = strlen( str ) - strlen( str ) % sizeofint );
    
const char* end  =  str + len ;
    
if ( *end )
    {
       cout 
<<   "有尾巴"  <<  endl;
    }
    
// 判断开头相等不
    
// 
    if ( hash == ptarget[index] )
    {
        cout 
<< "找到了" << endl;
    }
        
// 判断结尾相等不
// 以后再加吧。
    for( index = 0; index < len / 4 - 1; index++  )
    {
           
for( index2 = 8;index2 <= 32; index2 += 8 )
           {
               
// 向左移?向右移?视 big-endding 和 small-endding 不同而不同
               if ( hash ==  ( ( ptarget[index] >> index2 ) | ( ptarget[index+1<< ( 32- index2 ) ) ) )
               {
                   
break;
               }
           }
           
if(  index2 <= 32  )
           {
               posCollect.push_back( index 
* 4 + index2 / 8   );
           }
    }
    cout 
<<  "找到的次数:"    <<  posCollect.size()  << endl;
    
    
for(  vector<size_t>::const_iterator iter = posCollect.begin(); iter!= posCollect.end(); iter++  )
    {
        cout 
<< *iter    << endl;
    }
    system( 
"pause" );

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值