leetcode208-实现Trie(前缀树)

原题

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

示例:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // 返回 true
trie.search("app");     // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");   
trie.search("app");     // 返回 true

说明:

  • 你可以假设所有的输入都是由小写字母 a-z 构成的。
  • 保证所有输入均为非空字符串。

解法

思想

我之前的博客算法竞赛常用数据结构-字典树Trie有介绍字典树的结构,字典树的实现总是跟着需求来的,这道题需要判断是否有前缀和是否有整个单词,可以为节点设置一项属性isLeaf(是否是一个单词的结尾字符)。

代码

class Trie {
    class Node{
        boolean isLeaf = false;
        Node[] children = new Node[26];
    }
    Node root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new Node();
    }

    /** Inserts a word into the trie. */
    public void insert(String word) {
        char[] chars = word.toCharArray();
        Node node = root;
        for(int n = 0;n<chars.length;n++){
            if(node.children[chars[n]-'a'] == null)
                node = (node.children[chars[n]-'a'] = new Node());
            else
                node = node.children[chars[n]-'a'];
        }
        node.isLeaf = true;
    }

    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        char[] chars = word.toCharArray();
        Node node = root;
        for(int n = 0;n<chars.length;n++){
            if(node.children[chars[n]-'a'] == null)
                return false;
            else
                node = node.children[chars[n]-'a'];
        }
        if(node.isLeaf==false) return false;
        return true;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        char[] chars = prefix.toCharArray();
        Node node = root;
        for(int n = 0;n<chars.length;n++){
            if(node.children[chars[n]-'a'] == null)
                return false;
            else
                node = node.children[chars[n]-'a'];
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode208-%e5%ae%9e%e7%8e%b0trie%e5%89%8d%e7%bc%80%e6%a0%91/

(0)
彭晨涛彭晨涛管理者
上一篇 2020年2月21日
下一篇 2020年2月22日

相关推荐

发表回复

登录后才能评论