Skip to content
本页目录

题目描述

https://leetcode.cn/problems/implement-trie-prefix-tree

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

提示:

  • 1 <= word.length, prefix.length <= 2000
  • word 和 prefix 仅由小写英文字母组成
  • insert、search 和 startsWith 调用次数 总计 不超过 3 * 104 次

思路

使用hash表完成主要 Insert 和 Search 功能,对于 StartsWith 功能,遍历所有的 Key 然后依次判断,如果找到返回结果。

参考代码

csharp
public class Trie {

    Dictionary<string,int> dict ;

    public Trie() {
        dict = new Dictionary<string,int>();
    }
    
    public void Insert(string word) {
        if(!dict.ContainsKey(word)){
            dict.Add(word,1);
        }
    }
    
    public bool Search(string word) {
        return dict.ContainsKey(word);
    }
    
    public bool StartsWith(string prefix) {
        foreach(string key in dict.Keys){
            if(key.IndexOf(prefix) == 0 ){
                return true;
            }
        }
        return false;
    }
}

思路2:字典树【官方】

因为字母一共是26个字符,所以我们创建一个字典树,根开始,下面是26个child. 判断搜索的时候,看搜到的最后一位是不是结尾(没有子孩子) 判断前缀的时候,搜到就可以。

csharp
public class Trie{

	public Trie[] children;
	public bool 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 c = word[i];
			int index = c - 'a';
			if(node.children[index] == null){
				node.children[index] = new Trie();
			}
			node = node.children[index];
		}
		//最后一个节点的 isEnd = true; 
		node.isEnd = true;
	}

	public bool Search(string word){
		Trie node = searchPrefix(word);
		return node != null && node.isEnd;
	}

	public bool StartsWith(string prefix){
		return searchPrefix(prefix) != null;
	}

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

Released under the MIT License.