class Trie
{
Map<Character, Trie> child = new HashMap<>();
boolean isWord;
/** Initialize your data structure here. */
public Trie()
{
isWord = false;
}
/** Inserts a word into the trie. */
public void insert(String word)
{
Trie root = this;
for (int i = 0; i < word.length(); i ++)
{
char c = word.charAt(i);
if (root.child.containsKey(c) == false)
root.child.put(c, new Trie());
root = root.child.get(c);
}
root.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word)
{
Trie root = this;
for (int i = 0; i < word.length(); i ++)
{
char c = word.charAt(i);
if (root.child.containsKey(c) == false)
return false;
root = root.child.get(c);
}
return root.isWord == true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix)
{
Trie root = this;
for (int i = 0; i < prefix.length(); i ++)
{
char c = prefix.charAt(i);
if (root.child.containsKey(c) == false)
return false;
root = root.child.get(c);
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
字典树||前缀树Java
最新推荐文章于 2024-07-08 22:12:26 发布