Leecode no.208 实现Tire(前缀树)

package leecode;

import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
* Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
*
* 请你实现 Trie 类:
*
* Trie() 初始化前缀树对象。
* void insert(String word) 向前缀树中插入字符串 word 。
* boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
* boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
*  
*
* 2021/6/1
*/
public class Trie {

static Map<Character, Integer> characterMap = new HashMap<>();

static{
characterMap.put('a', 0);
characterMap.put('b', 1);
characterMap.put('c', 2);
characterMap.put('d', 3);
characterMap.put('e', 4);
characterMap.put('f', 5);
characterMap.put('g', 6);
characterMap.put('h', 7);
characterMap.put('i', 8);
characterMap.put('j', 9);
characterMap.put('k', 10);
characterMap.put('l', 11);
characterMap.put('m', 12);
characterMap.put('n', 13);
characterMap.put('o', 14);
characterMap.put('p', 15);
characterMap.put('q', 16);
characterMap.put('r', 17);
characterMap.put('s', 18);
characterMap.put('t', 19);
characterMap.put('u', 20);
characterMap.put('v', 21);
characterMap.put('w', 22);
characterMap.put('x', 23);
characterMap.put('y', 24);
characterMap.put('z', 25);
}

Trie[] children;

boolean end = false;

/** Initialize your data structure here. */
/**
* 一个Tile当作一个树的节点
* children对应当前节点的子节点
*/
public Trie() {
children = new Trie[26];
}

/** Inserts a word into the trie. */
public void insert(String word) {
if(word == null || "".equals(word)){
this.end = true;
return;
}
char c = word.toCharArray()[0];
Integer index = characterMap.get(c);
Trie child = children[index];
if(child == null){
children[index] = new Trie();
child = children[index];
}
child.insert(word.substring(1));
}

/** Returns if the word is in the trie. */
public boolean search(String word) {
if(word == null || "".equals(word)){
return end;
}
char c = word.toCharArray()[0];
Integer index = characterMap.get(c);
Trie child = children[index];
if(child == null){
return false;
}
return child.search(word.substring(1));
}

/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
if(prefix == null || "".equals(prefix)){
return true;
}
char c = prefix.toCharArray()[0];
Integer index = characterMap.get(c);
Trie child = children[index];
if(child == null){
return false;
}
return child.startsWith(prefix.substring(1));
}


public static void main(String[] args) {
String word = "apple";

Trie trie = new Trie();
trie.insert(word);

boolean search = trie.search("app");
System.out.println(search);
boolean startsWith = trie.startsWith("app");
System.out.println(startsWith);
}


}
posted @ 2021-06-01 15:17  六小扛把子  阅读(55)  评论(0编辑  收藏  举报