天天看点

LeetCode之团灭字典树相关话题

经典模板题

LeetCode208实现 Trie(前缀树)

Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

  • ​Trie()​

    ​ 初始化前缀树对象。
  • ​void insert(String word)​

    ​​ 向前缀树中插入字符串 ​

    ​word​

    ​ 。
  • ​boolean search(String word)​

    ​​ 如果字符串 ​

    ​word​

    ​​ 在前缀树中,返回 ​

    ​true​

    ​​(即,在检索之前已经插入);否则,返回 ​

    ​false​

    ​ 。
  • ​boolean startsWith(String prefix)​

    ​​ 如果之前已经插入的字符串 ​

    ​word​

    ​​ 的前缀之一为 ​

    ​prefix​

    ​​ ,返回 ​

    ​true​

    ​​ ;否则,返回 ​

    ​false​

    ​ 。

示例:

输入

["Trie", "insert", "search", "search", "startsWith", "insert", "search"]

[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]

输出

[null, null, true, false, true, null, true]

解释

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

解题思路

想象以下,包含三个单词 "sea","sells","she" 的 Trie 会长啥样呢?

LeetCode之团灭字典树相关话题

 定义类 Trie

class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
}      

插入

描述:向 Trie 中插入一个单词 word

实现:这个操作和构建链表很像。首先从根结点的子结点开始与 word 第一个字符进行匹配,一直匹配到前缀链上没有对应的字符,这时开始不断开辟新的结点,直到插入完 word 的最后一个字符,同时还要将最后一个结点isEnd = true;,表示它是一个单词的末尾。

public void insert(String word) {
     Trie node = this;
     for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
      }
      node.isEnd = true;
}      

前缀匹配

描述:判断 Trie 中是或有以 prefix 为前缀的单词

实现:和 search 操作类似,只是不需要判断最后一个字符结点的isEnd,因为既然能匹配到最后一个字符,那后面一定有单词是以它为前缀的。

public boolean startsWith(String prefix) {
     return searchPrefix(prefix) != null;
}

private Trie searchPrefix(String prefix) {
     Trie node = this;
     for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
      }
     return node;
}      

 查找

描述:查找 Trie 中是否存在单词 word

实现:从根结点的子结点开始,一直向下匹配即可,如果出现结点值为空就返回 false,如果匹配到了最后一个字符,那我们只需判断 node.isEnd即可。

public boolean search(String word) {
     Trie node = searchPrefix(word);
     return node != null && node.isEnd;
}      

代码实现

class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    private Trie searchPrefix(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (node.children[index] == null) {
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}      

相关拓展

LeetCode1233删除子文件夹

你是一位系统管理员,手里有一份文件夹列表 ​

​folder​

​,你的任务是要删除该列表中的所有 子文件夹,并以 任意顺序 返回剩下的文件夹。

如果文件夹 ​

​folder[i]​

​​ 位于另一个文件夹 ​

​folder[j]​

​​ 下,那么 ​

​folder[i]​

​​ 就是 ​

​folder[j]​

​ 的 子文件夹 。

文件夹的「路径」是由一个或多个按以下格式串联形成的字符串:'/'

  • 例如,​

    ​"/leetcode"​

    ​​ 和 ​

    ​"/leetcode/problems"​

    ​​ 都是有效的路径,而空字符串和 ​

    ​"/"​

    ​ 不是。

示例 1:

输入:folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
输出:["/a","/c/d","/c/f"]
解释:"/a/b/" 是 "/a" 的子文件夹,而 "/c/d/e" 是 "/c/d" 的子文件夹。      

示例 2:

输入:folder = ["/a","/a/b/c","/a/b/d"]
输出:["/a"]
解释:文件夹 "/a/b/c" 和 "/a/b/d/" 都会被删除,因为它们都是 "/a" 的子文件夹。      
输入: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
输出: ["/a/b/c","/a/b/ca","/a/b/d"]      

解题思路

代码实现

class Solution {
    public List<String> removeSubfolders(String[] folder) {
        Trie trie = new Trie();
        for (String i : folder) {
            trie.add(i);
        }
        List<String> ans = new ArrayList<>();
        for (String i : folder) {
            if (trie.ok(i)) {
                ans.add(i);
            }
        }
        return ans;
    }
}

class Trie {
    HashMap<String, Trie> child;
    boolean isEnd;
    
    public Trie() {
        this.child = new HashMap<>();
        this.isEnd = false;
    }

    public void add(String s) {
        Trie root = this;
        String[] arr = s.split("/");
        for (int i = 0; i < arr.length; i++) {
            if (!root.child.containsKey(arr[i])) {
                root.child.put(arr[i], new Trie());
            }
            root = root.child.get(arr[i]);
        }
        root.isEnd = true;
    }

    public boolean ok(String s) {
        Trie root = this;
        String[] arr = s.split("/");
        for (int i = 0; i < arr.length; i++) {
            root = root.child.get(arr[i]);
            //已有的路径已经到达末位,但是要检测的字符串还未到达末位,说明这是个子文件夹需要删除
            if (i != arr.length - 1 && root.isEnd) {
                return false;
            }
        }
        return true;
    }
}