10万个字符串,检查相同的.怎么找?

来源:互联网 发布:北京市软件行业协会 编辑:程序博客网 时间:2024/05/17 08:02
构建一个索引树!
讲课时用过这个例子,参考一下吧!

CODE:
[Copy to clipboard]
#define TREEWIDTH 256

typedef struct node_t {
        struct node_t *next[TREEWIDTH];
        int count;
} node_t;

/* 这个函数把一个word导入一个索引树,然后返回这个word以前曾经导入过多少次 */
int
indexword(node_t *head, const char *word)
{
        int i;
        node_t *cur,*new;

        for (i=0,cur=head;;++i) {
                if (word[i]=='/0') {
                        cur->count=cur->count+1;
                        if (cur->count > 1) {
                                return cur->count-1;
                        }
                        break;
                }
                if (cur->next[word[i]] == NULL) {
                        cur->next[word[i]] = (node_t*)malloc(sizeof(node_t));
                        if (cur->next[word[i]] == NULL) {
                                return -1;
                        }
                }
                cur=cur->next[word[i]];
        }

        return 0;
}
========================================================

字符串可以提前处理吗 ,如果字符串很少变化, 可以对字符串进行MD5编码, 的到MD5 列表, 然后对MD5列表排序, 得到MD5编码索引, 需要进行字符串查找时 , 先找具有相同MD5的字符串, 然后仔细比较, 速度应该很快的的 。
如过数据时变动很大的, MD5索引可以用,hash + 链表的方式 。 自持动态加载。

=================================================

可以直接将所有字符串排序,然后二分查找,这个也不慢的。

要算 hash 的话,也不需要 md5 那么复杂的,毕竟 md5 太长了,比较不方便。我习惯这样算 hash:

CODE:
[Copy to clipboard]
int hash_str(const char* str)
{
  int h = 0;
  while (*str)
    h = h * 5 + *str++;
  return h;
}

=======================================================





__________________________________