Trie

Posted 久诚keep

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Trie相关的知识,希望对你有一定的参考价值。

package jckeep.trie;

import java.util.*;


class TrieNode {
    public TrieNode[] children;
    public String word;

    public TrieNode() {
        children = new TrieNode[26];
    }
}


public class Trie {
    private TrieNode trie;

    public Trie() {
        trie = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = trie;
        for (int i = 0; i < word.length(); ++i) {
            char c = word.charAt(i);
            if (node.children[c - \'a\'] == null) {
                node.children[c - \'a\'] = new TrieNode();
            }
            node = node.children[c - \'a\'];
        }
        node.word = word;
    }

    public boolean search(String word) {
        if (word == null || word.length() == 0)
            return true;
        TrieNode node = trie;
        for (int i = 0; i < word.length(); ++i) {
            char c = word.charAt(i);
            if (node.children[c - \'a\'] == null)
                return false;
            node = node.children[c - \'a\'];
        }
        return (word.equals(node.word) ? true : false);
    }

    public boolean searchPrefix(String prefix) {
        if (prefix == null || prefix.length() == 0)
                        return true;
                TrieNode node = trie;
                for (int i = 0; i < prefix.length(); ++i) {
                        char c = prefix.charAt(i);
                        if (node.children[c - \'a\'] == null)
                                return false;
                        node = node.children[c - \'a\'];
                }
        return true;
    }
}

 

以上是关于Trie的主要内容,如果未能解决你的问题,请参考以下文章

天天数据结构和算法PHP中trie数据结构的使用场景和代码实例

trie树

trie树

java刷题--208Trie前缀树

java刷题--208Trie前缀树

Trie树题目模板及java代码