【问题标题】:Efficiently get subset of strings "startingWith" out of a set从集合中有效地获取字符串“startingWith”的子集
【发布时间】:2015-06-22 23:46:37
【问题描述】:

我有一组 字符串,我想为其创建一个自动建议功能。

假设集合是["foo", "fighter"]

输入"f" 应该返回两个值,输入"fo" 应该只返回"foo"

目前我只是通过调用startsWith 来遍历集合并归档结果,但是它太慢了。

标准的 TreeSet 及其子集函数在这里没有多大帮助,因为它只实现了一个 RB 树。

Java API 中是否有有效的解决方案,还是我必须构建自己的 Set 实现?


编辑: 我的实现看起来像这样,使用 Andrey Naumenkos trie datastructures。如果要使用扩展的 ASCII 字符,请注意增加数组大小。如果您使用List 而不是Map,您将按排序顺序获得结果。

public Set<String> getSubset(String s) {
    result = new HashSet<String>();
    getSubset(root, s);
    return result;
}

private void getSubset(TrieNode node, String s) {
    TrieNode n = node;
    for (char ch : s.toCharArray()) {
        if (n.children[ch] != null) {
            n = n.children[ch];
            continue;
        }
        return;
    }
    getSubsetR(n, s);
}

private void getSubsetR(TrieNode node, String s) {
    for (char ch = 0; ch < node.children.length; ch++) {
        TrieNode child = node.children[ch];
        if (child != null)
            getSubsetR(child, s + ch);
    }
    if (node.leaf) {
        result.add(s);
    }
}

【问题讨论】:

    标签: java algorithm dictionary substring subset


    【解决方案1】:

    你要找的是前缀树数据结构:http://en.wikipedia.org/wiki/Trie

    此处的代码将帮助您入门:https://sites.google.com/site/indy256/algo/trie

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多