字典与Trie的对比
字典:
如果有n个条目,使用树结构,查询的时间复杂度为O(logn)
如果有100w个条目(大约是2^20)logn大约为20
Trie:
查询每个条目的时间复杂度与条目数无关,时间复杂度为O(w),w为查询单词的长度。
Trie是怎么做到时间复杂度与条目数无关的呢?答案就在于它是如图所示的数据结构:
节点的定义:
由于指针数量的不确定性,我们不能直接把指针数量写死,应该采用动态的方式。
错误示范
class Node{
char c;
Node next[26];
}
动态方式
class Node{
char c;
Map<char, Node> next;
}
优化:想象我们在查找cat这个单词,显然在根节点时我们就已经知道要找的下一个节点是c,所以我们不需要把字符值写在节点上,应该写在边上,如下图所示:
然后继续考虑一个问题:怎么判断已经找到了需要的单词?
首先我们知道当查找到叶子节点时查询一定结束了,但是还有很多单词本身是其他单词的前缀,这时我们要判断的话就需要在节点中加入一个布尔值来表明当前字符串是否是一个英文单词。
所以节点的定义可以这样写:
class Node{
boolean isWord;
Map<char, Node> next;
}
完整的Trie结构:
import java.util.TreeMap;
/**
* className Trie
* description TODO
*
* @author ln
* @version 1.0
* @date 2019/6/29 19:19
*/
public class Trie {
private class Node{
public boolean isWord;
public TreeMap<Character, Node> next;
public Node(boolean isWord){
this.isWord = isWord;
next = new TreeMap<>();
}
public Node(){
this(false);
}
}
/**
* 字典树的根节点
*/
private Node root;
/**
* 字典树中存储的单词数量
*/
private int size;
public Trie(){
root = new Node();
size = 0;
}
public int getSize(){
return size;
}
public void add(String word){
Node cur = root;
/**
* 在字典树中按一个个字符查找传入的word参数
* 若字符c的下一个节点不存在,则在TreeMap中存入(c,new Node())
* 然后让当前节点的指针指向c对应的节点
*/
for (int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if (cur.next.get(c) == null){
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
/**
* 对于最后一个节点要注意首先判断它是否已经是一个单词的结尾
* 避免例如panda和pan的情况
*/
if (!cur.isWord){
cur.isWord = true;
size++;
}
}
}
Trie的查询
/**
* 查询单词word是否在Trie中
* @param word
* @return
*/
public boolean contains(String word){
Node cur = root;
for (int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if (cur.next.get(c) == null){
return false;
}
cur = cur.next.get(c);
}
/**
* 这里不能直接return true
* 以panda和pan为例,在查找pan时虽然cur指针确实走到了n这个节点
* 但是如果pan这个单词并未存储在Trie中(即n节点对应的isWord是false)
* 这种情况也是属于Trie中没有这个单词
*/
return cur.isWord;
}
Trie的前缀搜索
Trie又叫做前缀树,在搜索一个单词时在找到结尾前的节点都是要找的单词的前缀。
实现代码:
/**
* 在Trie中查找是否有单词以prefix为前缀
* @param prefix
* @return
*/
public boolean isPrefix(String prefix){
Node cur = root;
for (int i = 0; i < prefix.length(); i++){
char c = prefix.charAt(i);
if (cur.next.get(c) == null){
return false;
}
cur = cur.next.get(c);
}
return true;
}
这里的逻辑是一个单词本身也是它自己的前缀。
练习
211. 添加与搜索单词 - 数据结构设计
设计一个支持以下两种操作的数据结构:
void addWord(word)
bool search(word)
search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。
示例:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
说明:
你可以假设所有单词都是由小写字母 a-z 组成的。
思路:
本题与之前实现的Trie的区别就在于其加入了正则表达式中的“.”,“.”可以表示任意字符,因此在碰到.时我们需要遍历所有的可能来看后面的节点是否匹配后面的字符。
对于树形结构的遍历自然想到递归的方式,这里我们可以根据当前节点是不是“.”分两种情况处理。设当前要匹配的字符为c。
1.当前节点不是通配符
判断当前节点的next中是否有以c为key的节点,若没有则匹配失败。若有则递归匹配下一个字符。
2.当前节点是通配符
取出当前节点next的keySet进行递归遍历,全部匹配则返回true,遍历结束若没有返回true则返回false。
实现代码:
class WordDictionary {
private class Node{
public boolean isWord;
public TreeMap<Character, Node> next;
public Node(boolean isWord){
this.isWord = isWord;
next = new TreeMap<>();
}
public Node(){
this(false);
}
}
/**
* 字典树的根节点
*/
private Node root;
/** Initialize your data structure here. */
public WordDictionary() {
root = new Node();
}
/** Adds a word into the data structure. */
public void addWord(String word) {
Node cur = root;
for (int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if (cur.next.get(c) == null){
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
cur.isWord = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
public boolean search(String word) {
return match(root, word, 0);
}
private boolean match(Node node, String word, int index){
if (index == word.length()){
return node.isWord;
}
char c = word.charAt(index);
if (c != '.'){
if (node.next.get(c) == null){
return false;
}
return match(node.next.get(c), word, index + 1);
} else {
for (char nextChar : node.next.keySet()){
if (match(node.next.get(nextChar), word, index + 1)){
return true;
}
}
return false;
}
}
}
把Trie当作映射使用的情况
677. 键值映射
实现一个 MapSum 类里的两个方法,insert 和 sum。
对于方法 insert,你将得到一对(字符串,整数)的键值对。字符串表示键,整数表示值。如果键已经存在,那么原来的键值对将被替代成新的键值对。
对于方法 sum,你将得到一个表示前缀的字符串,你需要返回所有以该前缀开头的键的值的总和。
示例 1:
输入: insert("apple", 3), 输出: Null
输入: sum("ap"), 输出: 3
输入: insert("app", 2), 输出: Null
输入: sum("ap"), 输出: 5
题目大意:
要求实现一个映射关系和两个方法,insert方法可以在映射中插入(字符串,整数)的键值对,并且可以覆盖原来的键;sum方法是根据传入的字符串求出所有以该字符串为前缀的键对应的值的和。
思路:
用Trie来表示这个映射关系,insert方法没什么好说的,sum方法可以用递归实现,先找到传入的前缀最后一个字母对应的节点,然后用递归求出以当前节点为根的所有子树的value和。
实现代码:
class MapSum {
private class Node{
public int value;
public TreeMap<Character, Node> next;
public Node(int value){
this.value = value;
next = new TreeMap<>();
}
public Node(){
this(0);
}
}
private Node root;
/** Initialize your data structure here. */
public MapSum() {
root = new Node();
}
public void insert(String key, int val) {
Node cur = root;
for (int i = 0; i < key.length(); i++){
char c = key.charAt(i);
if (cur.next.get(c) == null){
cur.next.put(c, new Node());
}
cur = cur.next.get(c);
}
cur.value = val;
}
public int sum(String prefix) {
Node cur = root;
for(int i = 0; i < prefix.length(); i++){
char c = prefix.charAt(i);
if (cur.next.get(c) == null){
return 0;
}
cur = cur.next.get(c);
}
return sum(cur);
}
/**
* 递归求出以当前节点为根所有子树的value和
* @param node
* @return
*/
private int sum(Node node){
int res = node.value;
for (char c : node.next.keySet()){
res += sum(node.next.get(c));
}
return res;
}
}
Trie的局限性
最大的问题:空间。
private class Node{
public boolean isWord;
public TreeMap<Character, Node> next;
}
在英语环境中如果不区分大小写,这个map就会存储26个键值对,这与原来只存储一个字符相比空间大了几十倍。
Writtern by Autu.
2019.7.1