2013-02-05 13 views
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; 
} 

可这不是最佳的多吗?

+2

[Rabin-Karp algorithm](http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm)? –

+1

这被称为字符串搜索。有很多算法可以使这个更高效,尽管它们可能有些复杂。 –

+0

@VaughnCato为什么要创建评论而不是答案? – junix

回答

3
+0

我在C中发现了Rabin-Karp的这个实现:http://www.geeksforgeeks.org/searching-for-patterns-set-3-rabin-karp-algorithm/但是它失败了:'pattern =“\ XFF“;文字= “\ X00 \ XFF”'。你知道如何解决这个问题吗? – Tyilo

+0

想想。字符串以NUL结尾,strlen(“\ x00 \ xff”)是什么? –

+0

@Alexey_Frunze对不起,我忘了说我用函数的参数替换了'N'和'M'的'strlen'。它仍然没有找到它。像这样:http://pastebin.com/iwVGymQg – Tyilo

相关问题