LintCode 556: Standard Bloom Filter (System Design题)

  1. Standard Bloom Filter

Implement a standard bloom filter. Support the following method:

StandardBloomFilter(k) The constructor and you need to create k hash functions.
add(string) Add a string into bloom filter.
contains(string) Check a string whether exists in bloom filter.
Example
Example1

Input:
StandardBloomFilter(3)
add(“lint”)
add(“code”)
contains(“lint”)
contains(“world”)
Output: [true,false]
Example2

Input:
StandardBloomFilter(10)
add(“hello”)
contains(“hell”)
contains(“helloa”)
contains(“hello”)
contains(“hell”)
contains(“helloa”)
contains(“hello”)
Output: [false,false,true,false,false,true]

解法1:参考的网上的答案。
注意:

  1. Bloom Filter的
    add()的主要思想是用多个hash方程来将输入map到bit串中的若干位,并对这些位都设1。contains()的主要思想是用多个hash方程将输入map到bit串中的若干位,若这些位都为1,则返回true;有一个或多位为0,则返回false。
    用一句话来总结Bloom Filter的主要思想就是:全真未必真,有假必定假。
  2. hash方程的cap和seed可以随意。seed越大则map得越均匀。
  3. stl的bitset很好用。bitset<200000>是设一个200000位的bit串。 bitset.set(100)是将第100位置1。
#include <bitset>

class HashClass{
public:
    HashClass(int c, int s) : cap(c), seed(s) {}
        
    int hashFunc(string &value) {
        int ret = 0;
        for (int i = 0; i < value.size(); ++i) {
            ret += seed * ret + value[i];
            ret %= cap;
        }
        return ret;
    }
private:
    int cap, seed;
};

class StandardBloomFilter {
public:
    /*
    * @param k: An integer
    */
    StandardBloomFilter(int k) {
       this->k = k;
       for (int i = 0; i < k; ++i) {
           hashVec.push_back(new HashClass(100000 + i, 2 * i + 3));
       }
    }

    /*
     * @param word: A string
     * @return: nothing
     */
    void add(string &word) {
        for (int i = 0; i < k; ++i) {
            bits.set(hashVec[i]->hashFunc(word));
        }
    }

    /*
     * @param word: A string
     * @return: True if contains word
     */
    bool contains(string &word) {
        for (int i = 0; i < k; ++i) {
            if (!bits[hashVec[i]->hashFunc(word)])
                return false;
        }
        return true;
    }

private:
    int k;
    vector<HashClass *> hashVec;
    bitset<200000> bits;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值