c - 如何有效地找到另一个数组中子数组的所有匹配项?

标签 c arrays search optimization

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

#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;
}

这个能不能再优化一下?

最佳答案

关于c - 如何有效地找到另一个数组中子数组的所有匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14701755/

相关文章:

c - OpenMP 实现还原

c - 为什么 access(2) 检查真实的 UID 而不是有效的 UID?

java - 在 Java 中,如何将大数存储在数组中?

javascript - 无法将数组作为数组进行操作

regex - 如何在 sublime 文本的范围内进行 vi 搜索和替换

swift - 在结构中搜索,传递数组的索引?

c - %d 的 sscanf 格式字符串显式匹配

arrays - 转置满足条件的行中的值

php - 使用php在多维数组中获取父数组键的最快方法

c# - 从 C# 与 C 对话