用Boyer-Moore-Horspool向后搜索

时间:2018-05-08 21:49:05

标签: c++ string algorithm search pattern-matching

我已经实施了Boyer-Moore-Horspool搜索算法,当我想在我的文本中向前搜索时它非常有用。我试图让它适应倒退,并且似乎无法做到正确。

是否有使用BMH向后搜索的示例?

作为参考,这是我的代码:

POSITION_T cDocument::FindNext(std::string needle, POSITION_T start)
{
    size_t buffersize = mBuffer.GetByteSize() ;
    size_t needlesize = needle.length() ;
    vector<int> badchars(256, -1) ;

    BadCharHueristic(needle, badchars) ;

    size_t s = mBuffer.ConvertPositionToByte(start) ;
    while(s <= (buffersize - needlesize))
    {
        ssize_t j = needlesize - 1 ;

        while(j >= 0 && needle[j] == mBuffer.GetByte(s + j))
        {
            j-- ;
        }

        if(j < 0)
        {
            // s holds our position in bytes
            return mBuffer.ConvertByteToPosition(s) ;
        }
        else
        {
            ssize_t b = j - badchars[mBuffer.GetByte(s + j)] ;
            s += Max(1, b) ;
        }
    }

    return GetTextSize() ;
}

1 个答案:

答案 0 :(得分:1)

//Java Solution

public static int findLastBoore(char[] text, char[] pattern) {

    int n = text.length;
    int m = pattern.length;

    if (m == 0) return 0;
    Map<Character, Integer> last = new HashMap<Character, Integer>();
    
    for (int i = 0; i < n; i++) {
        last.put(text[i], -1);
    }
    for (int k = 0; k < m; k++){
        last.put(pattern[k], k);
    }   
    int i = n - m;
    int k = 0;

    while (i > 0) {
        if (text[i] == pattern[k]) {
            if (k == m - 1) return i;
            i++;
            k++;
        } else {
            // Step backwards when there is a mismatch
            i-= m - Math.max(k + 1, last.get(text[i]));
            k = 0;
        }
        
    }
    return -1;
}

`