【问题标题】:How to efficiently find all matches of an subarray in another array?如何有效地找到另一个数组中子数组的所有匹配项?
【发布时间】:2013-01-20 00:55:58
【问题描述】:

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

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

这个不能再优化一下吗?

【问题讨论】:

  • 这称为字符串搜索。有许多算法可以提高效率,尽管它们可能有些复杂。
  • @VaughnCato 为什么要创建评论而不是答案?
  • @AlexeyFrunze 抄送给你 :-)
  • @junix 是的,是的,帽子! :)

标签: c arrays search optimization


【解决方案1】:

【讨论】:

  • 我在 C:geeksforgeeks.org/… 中找到了 Rabin-Karp 的这个实现,但是它失败了:pattern="\xff"; text="\x00\xff"。你知道如何解决这个问题吗?
  • 想一想。字符串以 NUL 结尾,strlen("\x00\xff") 是什么?
  • @Alexey_Frunze 抱歉,我忘了说我用函数的参数替换了NMstrlen。它仍然没有找到它。像这样:pastebin.com/iwVGymQg
  • 调试代码。如果您了解算法并知道如何使用调试器,您应该能够做到。
  • @Alexey_Frunze 这是因为检查了t 的负值,因为chars 不是无符号的,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 2017-03-01
  • 2013-11-06
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
相关资源
最近更新 更多