用于电话簿应用程序中的有效子字符串搜索的数据结构

时间:2016-11-09 09:31:49

标签: algorithm data-structures

我想在电话簿上存储联系人, 我希望用户只搜索名称的一部分。

例如: 电话簿包含:

Tom, John, Eve, Barbi ,Johnathon. 

现在,用户搜索" hn" ,结果需要是" John"和#34; Johnathon"。

我读过关于TRIE的内容,但它只适用于前缀。

由于

3 个答案:

答案 0 :(得分:2)

通常在电话簿中

  1. 条目数量不是很大。

  2. 添加/删除/修改条目的频率远低于搜索条目。

  3. 因此,我建议您维护一个哈希表,将子字符串映射到它们出现的条目列表。修改条目时应修改此哈希表。

    例如,假设您添加长度为 n 的新条目。此条目最多包含 n 2 子字符串。对于每个这样的子字符串:

    1. 如果它不在哈希表中,请添加一个将子字符串映射到空列表的条目。

    2. 无论是否在哈希表中,都要将此条目添加到与子字符串对应的列表中(只需确保不要将其添加两次)。

    3. 如果你有 m 字,最长的字是 n ,那么 O(mn 2 应该足以存储一切。对于典型的电话簿,这很小。

答案 1 :(得分:0)

对于大多数人来说,他们的地址簿中的条目不到1000个。你可以通过子串搜索" hn"在每个名字中,依次。

在Python中的东西:

results = [name for name in address_book if name.contains(search_term)]

答案 2 :(得分:0)

如果我开发你的项目,那将是我的解决方案;下面的代码只是伪代码,你可以在每种编程语言中尝试这个

result;
booklist;
search_keyword;
if(length(search_keyword) == 1) //people generaly types first char of the name to find him/his in their list.
    for i=0 to n //traverse 0 to n
        if(booklist[i][0] == search_keyword[0]) //check first letter with booklist element and search_keyword
            result.push(booklist[i]);

if(length(search_keyword) == 2) //people generaly types first two letter of the name to find him/his in their list.
    for i=0 to n //traverse 0 to n
        if(booklist[i][0] == search_keyword[0] AND booklist[i][1] == search_keyword[1]) //check first letter with booklist element and search_keyword
            result.push(booklist[i]);

if(length(search_keyword) > 2)
    for i=0 to n //traverse 0 to n
        if(booklist[i].contains(search_keyword))
            result.push(booklist[i]);

return result;

在此算法中,大多数用户将等待O(n)时间复杂度。