Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
思路:
之前也没有接触过Trie,百科上查了一下,大概就是词源的问题,N个word有公共前缀,只是后缀不同,可以用树表示。
可以通过递归解决。
代码如下:
class TrieNode {
// 应该都是private的;只是为了减少代码量
// Initialize your data structure here.
public Map<Character,TrieNode> map;//存放后缀
public char val;//当前节点的字符值
public boolean tail;//一个字符串以该节点结尾
public TrieNode() {
map = new HashMap<>();
tail=false;
}
public TrieNode(char c) {
map = new HashMap<>();
this.val=c;
tail=false;
}
}
public class Trie {
private TrieNode root;
public Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
public void insert(String word) {
insert(root,word);
}
private void insert(TrieNode root,String word){
if(word.length()==0){
root.tail=true;
return;
}
TrieNode cur=root;
char c=word.charAt(0);
if(cur.map.containsKey(c)){
TrieNode child = cur.map.get(c);
insert(child,word.substring(1));
}else{
TrieNode child = new TrieNode(c);
cur.map.put(c,child);
insert(child,word.substring(1));
}
}
// Returns if the word is in the trie.
public boolean search(String word) {
return search(root,word);
}
private boolean search(TrieNode root,String word){
if(word.length()==0)
return root.tail==true;
char c = word.charAt(0);
if(!root.map.containsKey(c))
return false;
TrieNode child = root.map.get(c);
return search(child,word.substring(1));
}
// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
return startsWith(root,prefix);
}
private boolean startsWith(TrieNode root,String prefix) {
if(prefix.length()==0)
return true;
char c = prefix.charAt(0);
if(!root.map.containsKey(c))
return false;
TrieNode child = root.map.get(c);
return startsWith(child,prefix.substring(1));
}
}
// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
时间: 2024-10-09 19:46:57