您好,欢迎来到年旅网。
搜索
您的当前位置:首页利用Trie树,来查找单词出现的次数

利用Trie树,来查找单词出现的次数

来源:年旅网
  • Trie节点
class TrieNode {
    TrieNode nodes[];
    boolean isSentence; //称为一个句子的话仍然可能会有子节点
    int count; //表示当前节点实际上代表了多少个相同的单词

    public TrieNode() {
        nodes = new TrieNode[26]; //26个英文字母
        isSentence = false;
        count = 0;

    }
}
  • 构造Trie树,以及查找节点
//单论小写字母
void buildTrie(String str, TrieNode root) {
    if (root == null)
        return;
    TrieNode curr = root;
    char[] arr = str.toCharArray();
    for (int i = 0; i < arr.length; ++i) {
        if (curr.nodes[arr[i] - 'a'] == null) {
            curr.nodes[arr[i] - 'a'] = new TrieNode();
        }
        curr = curr.nodes[arr[i] - 'a'];
        if (i == arr.length - 1) {
            curr.isSentence = true;
            curr.count++;
        }
    }
}

int findStr(String str, TrieNode root) {
    if (root == null)
        return 0;
    TrieNode curr = root;
    char arr[] = str.toCharArray();
    for (int i = 0; i < arr.length; ++i) {
        if (curr.nodes[arr[i] - 'a'] == null)
            return 0;
        curr = curr.nodes[arr[i] - 'a'];
        if (arr.length - 1 == i && curr.isSentence) {
            return curr.count;
        }
    }
    return 0;
}
  • 测试一下:
public static void main(String[] args) {
    print p = new print();
    TrieNode node = new TrieNode();
    p.buildTrie("wangcheng", node);
    p.buildTrie("abc", node);
    p.buildTrie("abc", node);
    p.buildTrie("hello", node);
    p.buildTrie("hello", node);
    int a = p.findStr("wangcheng", node);
    System.out.println(a);
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务