1

例如,这是我现在实现它的方式:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

size_t *find_matches(char *needle, size_t needleSize, char *haystack, size_t haystackSize, size_t *size) {
    size_t max_matches = 256;
    size_t *matches = malloc(sizeof(size_t) * max_matches);
    int matchCount = 0;
    for(int i = 0; i + needleSize <= haystackSize; i++) {
        bool matched = true;
        for(int j = 0; j < needleSize; j++) {
            if(haystack[i + j] != needle[j]) {
                matched = false;
                break;
            }
        }

        if(matched) {
            matches[matchCount] = i;
            matchCount++;
            if(matchCount == max_matches) {
                break;
            }
        }
    }
    *size = matchCount;
    return matches;
}

int main() {
    char needle[] = {0xed, 0x57, 0x35, 0xe7, 0x00};
    char haystack[] = {0xed, 0x57, 0x35, 0xe7, 0x00, ..., 0xed, 0x57, 0x35, 0xe7, 0x00, ...};
    size_t size;
    size_t *matches = find_matches(needle, sizeof(needle), haystack, sizeof(haystack), &size);

    for(size_t i = 0; i < size; i++) {
        printf("Match %zi: %zi\n", i, matches[i]);
    }

    return 0;
}

这不能再优化吗?

4

1 回答 1

3

请参阅Rabin-Karp 算法和其他算法(Knuth-Morris-Pratt 算法Boyer-Moore 算法)。

于 2013-02-05T08:13:04.847 回答