Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

题目的要求很简单,完成一个前缀树的插入,搜索等功能。

Trie为前缀树,又称字典树或单词查找树,是一种用于快速检索的多叉树结构,例如,基于英文字母的前缀树是一个26叉树(a-z),基于数字的前缀树是一个10叉树(0-9)。前缀树的核心思想是用空间换时间。利用字符串的公共前缀来降低查询时间的开销,从而可以提高效率。前缀树的缺点是如果系统中存在大量字符串,并且这些字符串基本没有公共前缀,此时需要占用大量的内存。有关前缀树的基本性质大家可以网上查询,这里不再赘述。

对于这道题目有一个search方法用来查询字典中是否存在这个单词,startsWith方法用来检查是否存在一个前缀。因此实现search方法时我们要借助一个变量isLast来判段,字典中这个是否为一个完整的单词。代码如下:

class TrieNode {
TrieNode[] trieNode;
boolean isLast;
// Initialize your data structure here.
public TrieNode() {
trieNode = new TrieNode[26];
isLast = false;
}
}

public class Trie {
private TrieNode root;

public Trie() {
root = new TrieNode();
}

// Inserts a word into the trie.
public void insert(String word) {
TrieNode cur = root;
for(char c : word.toCharArray()) {
if(cur.trieNode[c - 'a'] == null)
cur.trieNode[c - 'a'] = new TrieNode();
cur = cur.trieNode[c - 'a'];
}
cur.isLast = true;
}

// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode cur = root;
if(root == null) return false;
for(char c : word.toCharArray()) {
if(cur.trieNode[c - 'a'] == null) return false;
cur = cur.trieNode[c - 'a'];
}
if(cur.isLast == true) return true;
return false;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode cur = root;
if(root == null) return false;
for(char c : prefix.toCharArray()) {
if(cur.trieNode[c - 'a'] == null) return false;
cur = cur.trieNode[c - 'a'];
}
return true;
}
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值