匹配位串

sci*_*ete 7 c++ string-search

我需要实现一个字符串搜索算法,该算法在位文本中找到位模式(匹配可能不是字节/字对齐).对于初学者,我实现了Boyer-Moore算法,但比较单个位对于我的目的来说太慢了.所以我尝试实现一个基于阻塞的版本,可以比较本文所述的整个字节/单词,但它已变得复杂且无法管理(部分原因是由于我不完全理解我在做什么.)

有没有人有这样的算法很好的实现?

我的具体用例是模式长度N >= 32,文本窗口2N和打包成ints的位.同样N在这种情况下是字符大小的倍数N % 8 == 0.我预处理一次并多次使用更改文本,比如Boyer-Moore.第一场比赛就是我所需要的.表现是关键.

编辑:在成功实现Blocked Boyer-Moore算法后,我注意到没有任何改进(我的一点一点版本更快!)这可能是我自己的错误,因为我一直在绞尽脑汁并优化它到目前为止没有多行评论就没有意义,但它仍然较慢.在这里.

U00*_*07D 3

概述

我是 SO 社区的新手,但我期待着回馈社会。

有趣的问题。我组合了一个实现,它只进行基于字节的比较(借助预先计算的位模式和位掩码),而不是在比较时执行昂贵的位操作。因此,它应该相当快。它没有实现针对Boyer-Moore 算法讨论的任何移位规则(性能优化) ,因此可以进一步改进。

尽管此实现确实取决于模式位数 % CHAR_BIT == 0 - 在 8 位机器上,满足 N % 8 == 0 的标准,但该实现将找到非字节对齐的位模式。(目前它还需要 8 位字符( CHAR_BIT == 8 ),但万一您的系统不使用 8 位字符,可以通过将所有数组/向量从 uint8_t 更改为 char 并调整来轻松适应它们包含的值反映了正确的位数。)

鉴于搜索不进行任何位操作(除了预先计算的字节掩码之外),它应该具有相当高的性能。

算法总结

简而言之,指定要搜索的模式,实现将其移位一位并记录移位后的模式。它还计算移位模式的掩码,对于非字节对齐的位模式,为了正确的行为,需要忽略比较开始和结束的一些位。

对每个移位位置中的所有模式位进行搜索,直到找到匹配或到达数据缓冲区的末尾。

//
//  BitStringMatch.cpp
//

#include "stdafx.h"
#include <iostream>
#include <cstdint>
#include <vector>
#include <memory>
#include <cassert>

int _tmain(int argc, _TCHAR* argv[])
{
    //Enter text and pattern data as appropriate for your application.  This implementation assumes pattern bits % CHAR_BIT == 0
    uint8_t text[] = { 0xcc, 0xcc, 0xcc, 0x5f, 0xe0, 0x1f, 0xe0, 0x0c }; //1010 1010, 1010 1010, 1010 1010, 010*1 1111, 1110 0000, 0001 1111, 1110 0000, 000*0 1010 
    uint8_t pattern[] = { 0xff, 0x00, 0xff, 0x00 }; //Set pattern to 1111 1111, 0000 0000, 1111 1111, 0000 0000

    assert( CHAR_BIT == 8 ); //Sanity check
    assert ( sizeof( text ) >= sizeof( pattern ) ); //Sanity check

    std::vector< std::vector< uint8_t > > shiftedPatterns( CHAR_BIT, std::vector< uint8_t >( sizeof( pattern ) + 1, 0 ) );  //+1 to accomodate bit shifting of CHAR_BIT bits.
    std::vector< std::pair< uint8_t, uint8_t > > compareMasks( CHAR_BIT, std::pair< uint8_t, uint8_t >( 0xff, 0x00 ) );

    //Initialize pattern shifting through all bit positions
    for( size_t i = 0; i < sizeof( pattern ); ++i ) //Start by initializing the unshifted pattern
    {
        shiftedPatterns[ 0 ][ i ] = pattern[ i ];
    }

    for( size_t i = 1; i < CHAR_BIT; ++i )  //Initialize the other patterns, shifting the previous vector pattern to the right by 1 bit position
    {
        compareMasks[ i ].first >>= i;  //Set the bits to consider in the first...
        compareMasks[ i ].second = 0xff << ( CHAR_BIT - i ); //and last bytes of the pattern

        bool underflow = false;
        for( size_t j = 0; j < sizeof( pattern ) + 1; ++j )
        {
            bool thisUnderflow = shiftedPatterns[ i - 1 ][ j ] & 0x01 ? true : false; 
            shiftedPatterns[ i ][ j ] = shiftedPatterns[ i - 1][ j ] >> 1;

            if( underflow ) //Previous byte shifted out a 1; shift in a 1
            {
                shiftedPatterns[ i ][ j ] |= 0x80;  //Set MSb to 1
            }

            underflow = thisUnderflow;
        }
    }

    //Search text for pattern
    size_t maxTextPos = sizeof( text ) - sizeof( pattern );
    size_t byte = 0;
    bool match = false;
    for( size_t byte = 0; byte <= maxTextPos && !match; ++byte )
    {
        for( size_t bit = 0; bit < CHAR_BIT && ( byte < maxTextPos || ( byte == maxTextPos && bit < 1 ) ); ++bit )
        {
            //Compare first byte of pattern
            if( ( shiftedPatterns[ bit ][ 0 ] & compareMasks[ bit ].first ) != ( text[ byte ] & compareMasks[ bit ].first ) )
            {
                continue;
            }

            size_t foo = sizeof( pattern );
            //Compare all middle bytes of pattern
            bool matchInProgress = true;
            for( size_t pos = 1; pos < sizeof( pattern ) && matchInProgress; ++pos )
            {
                matchInProgress = shiftedPatterns[ bit ][ pos ] == text[ byte + pos ];
            }
            if( !matchInProgress )
            {
                continue;
            }

            if( bit != 0 )  //If compare failed or we're comparing the unshifted pattern, there's no need to compare final pattern buffer byte
            {
                if( ( shiftedPatterns[ bit ][ sizeof( pattern ) ] & compareMasks[ bit ].second ) != ( text[ byte + sizeof( pattern ) ] & compareMasks[ bit ].second ) )
                {
                    continue;
                };
            }

            //We found a match!
            match = true;   //Abandon search
            std::cout << "Match found!  Pattern begins at byte index " << byte << ", bit position " << CHAR_BIT - bit - 1 << ".\n";
            break;
        }
    }
    //If no match
    if( !match )
    {
        std::cout << "No match found.\n";
    }

    std::cout << "\nPress a key to exit...";
    std::getchar();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我希望这是有帮助的。