Trie树、字典树

目录

208. 实现 Trie (前缀树)

720. 词典中最长的单词


208. 实现 Trie (前缀树)

Trie树、字典树_第1张图片

 class Trie {
    class TrieNode {
        boolean end;
        TrieNode[] next = new TrieNode[26];
    }

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

    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.next[u] == null) p.next[u] = new TrieNode();  //未创建就创建
            p = p.next[u];  //已创建就继续下一个
        }
        p.end = true;  //最后设置为真,说明有以此节点结尾的单词
    }

    public boolean search(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.next[u] == null) return false;  //遇到了不同的单词,直接false
            p = p.next[u];  //否则继续下探
        }
        return p.end;  //最后返回end,确定是否有以此节点结尾的单词
    }

    public boolean startsWith(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if (p.next[u] == null) return false;
            p = p.next[u]; 
        }
        return true;  //和search()类似,返回true说明找到前缀,否则for中就return了
    }
}

720. 词典中最长的单词

Trie树、字典树_第2张图片

class Solution {
    public String longestWord(String[] words) {
        Arrays.sort(words);
        String ans = "";
        Trie trie = new Trie();
        for(String s : words) {
            trie.insert(s);
            if(trie.inDictionary(s) && s.length() > ans.length())  ans = s;  //排序后已是字典序
        }
        return ans;
    }
}

class Trie {
    class TrieNode {
        boolean end;
        TrieNode[] next = new TrieNode[26];
    }

    //自定义无参构造函数
    TrieNode root;
    Trie() {
        root = new TrieNode();
    }

    public void insert(String s) {
        TrieNode p = root;
        for(int i = 0 ; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if(p.next[u] == null) p.next[u] = new TrieNode();
            p = p.next[u];
        }
        p.end = true;
    }

    public boolean search(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if(p.next[u] == null)  return false;
            p = p.next[u];
        }
        return p.end;
    }

    public boolean startsWith(String s) {
        TrieNode p = root;
        for(int i = 0; i < s.length(); i++) {
            int u = s.charAt(i) - 'a';
            if(p.next[u] == null) return false;
            p = p.next[u];
        }
        return true;
    }

    public boolean inDictionary(String s) {
        TrieNode p = root;
        for(char c : s.toCharArray()) {
            if(p.next[c-'a'] == null || !p.next[c - 'a'].end) {  //不是前缀或节点end不为true
                return false;
            }
            p = p.next[c-'a'];
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode,java,数据结构)