208. 实现 Trie (前缀树)
程序员文章站
2022-03-24 14:13:10
...
题目:
题解:
1. 定义类 TrieNode
class TrieNode
{
private boolean isEnd; //该结点是否是一个串的结束
TrieNode next[]; //字母映射表 next
public TrieNode()
{
isEnd = false;
next = new TrieNode[26];
}
}
2. 插入
3. 查找
4. 前缀匹配
代码:
public class code208 {
class Trie {
class TrieNode
{
private boolean isEnd; //该结点是否是一个串的结束
TrieNode next[]; //字母映射表 next
public TrieNode()
{
isEnd = false;
next = new TrieNode[26];
}
}
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 = root;
char c[] = word.toCharArray();
for(int i = 0; i < c.length; i++)
{
if(node.next[c[i] - 'a'] == null)
{
node.next[c[i] - 'a'] = new TrieNode();
}
node = node.next[c[i] - 'a'];
}
node.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = root;
char c[] = word.toCharArray();
for(int i = 0; i < c.length; i++)
{
node = node.next[c[i] - 'a'];
if(node == null)
{
return false;
}
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = root;
char c[] = prefix.toCharArray();
for(int i = 0; i < c.length; i++)
{
node = node.next[c[i] - 'a'];
if(node == null)
{
return false;
}
}
return true;
}
}
public static void main(String[] args) {
code208 solution = new code208();
Trie trie = solution.new Trie();
trie.insert("apple");
boolean res1 = trie.search("apple"); // 返回 true
boolean res2 = trie.search("app"); // 返回 false
boolean res3 =trie.startsWith("app"); // 返回 true
trie.insert("app");
boolean res4 = trie.search("app"); // 返回 true
System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
System.out.println(res4);
}
}