第15个算法-实现 Trie (前缀树)(LeetCode)
第15个算法-实现 Trie (前缀树)(LeetCode)
解法代码来源 :https://blog.csdn.net/whdAlive/article/details/81084793
算法来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree
实现一个 Trie (前缀树),包含 insert
, search
, 和 startsWith
这三个操作。
示例:
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
说明:
- 你可以假设所有的输入都是由小写字母
a-z
构成的。 - 保证所有输入均为非空字符串。
网上找了一些解法
class Trie {
//根节点
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
//初始化根节点
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = this.root;
//遍历
for(char c: word.toCharArray()){
if(node.children[c-‘a’]==null){
node.children[c-‘a’]=new TrieNode();
}
node = node.children[c-‘a’];
}
node.item = word;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = this.root;
//遍历
for(char c:word.toCharArray()){
if(node.children[c-‘a’]==null){
return false;
}
node = node.children[c-‘a’];
}
return node.item.equals(word);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = this.root;
//遍历
for(char c: prefix.toCharArray()){
if(node.children[c-‘a’]==null){
return false;
}
node = node.children[c-‘a’];
}
return true;
}
//定义 前缀树节点 的结构
class TrieNode{
//孩子节点,分别记录26个字母
TrieNode[] children = new TrieNode[26];
//当前的节点(叶子节点)对应的单词
String item = “”;
}
}
提交后优秀解法
class Trie {
private static class TrieNode {
boolean isExist;
TrieNode[] nodes;
TrieNode() {
isExist = false;
nodes = new TrieNode[26];
}
TrieNode put(char c) {
if (nodes[c-'a'] == null) {
nodes[c-'a'] = new TrieNode();
}
return nodes[c-'a'];
}
TrieNode get(char c) {
return nodes[c-'a'];
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
curr = curr.put(c);
}
curr.isExist = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
curr = curr.get(c);
if (curr == null) {
return false;
}
}
return curr.isExist;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode curr = root;
for (char c : prefix.toCharArray()) {
curr = curr.get(c);
if (curr == null) {
return false;
}
}
return true;
}
}
每天看一些算法,没有时间去研究,只能学习。
posted on 2019-07-27 11:36 liutian1912 阅读(…) 评论(…) 编辑 收藏