Description
中文English
Implement a counting bloom filter. Support the following method:
add(string)
. Add a string into bloom filter.contains(string)
. Check a string whether exists in bloom filter.remove(string)
. Remove a string from bloom filter.
Have you met this question in a real interview?
Example
Example1
Input:
CountingBloomFilter(3)
add("lint")
add("code")
contains("lint")
remove("lint")
contains("lint")
Output:
[true,false]
Example2
Input:
CountingBloomFilter(3)
add("lint")
add("lint")
contains("lint")
remove("lint")
contains("lint")
Output:
[true,true]
Code (java):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | class HashFunction { private int size; private int base; public HashFunction( int size, int base) { this .size = size; this .base = base; } public int hash(String str) { int hashCode = 0 ; for ( int i = 0 ; i < str.length(); i++) { hashCode = ( int )((( long )hashCode * base + Integer.valueOf(str.charAt(i))) % size); } return hashCode; } } public class CountingBloomFilter { private List<HashFunction> hashFunctions; private int [] bloomFilter; /* * @param k: An integer **/ public CountingBloomFilter(int k) { // do intialization if necessary hashFunctions = new ArrayList<>(); for (int i = 0; i < k; i++) { HashFunction func = new HashFunction(100000, 2 * i + 3); hashFunctions.add(func); bloomFilter = new int[100000]; } } /* * @param word: A string * @return: nothing */ public void add(String word) { // write your code here for (HashFunction hashFunc : hashFunctions) { int hashCode = hashFunc.hash(word); bloomFilter[hashCode] += 1; } } /* * @param word: A string * @return: nothing */ public void remove(String word) { // write your code here for (HashFunction hashFunc : hashFunctions) { int hashCode = hashFunc.hash(word); bloomFilter[hashCode] -= 1; } } /* * @param word: A string * @return: True if contains word */ public boolean contains(String word) { // write your code here for (HashFunction hashFunc : hashFunctions) { int hashCode = hashFunc.hash(word); if (bloomFilter[hashCode] <= 0 ) { return false ; } } return true ; } } |