利用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);
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/eversliver/article/details/52527002
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞