雜湊尋找字串

來源:互聯網
上載者:User

雜湊尋找的優越性:
當尋找的字串長度小於機器字長時,可以把字串當做 long 進行比較。由於移位操作相當快(一個刻度),所以執行操作花費的時間比較少。
這種尋找辦法通用性不好。( big-endian or little-endian 問題)。但不可否認,它的尋找速度確實快。

// "CSDN" 的尋找演算法
// 思路是:把 "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 ) % sizeof( int );
    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" );

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.