字典树——入门学习(java代码实现)
Posted 小乖乖的臭坏坏
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字典树——入门学习(java代码实现)相关的知识,希望对你有一定的参考价值。
Trie.java
public class Trie
class TrieNode
boolean isWord = false;
TrieNode[] children; // HashMap<Character, TrieNode> children
public TrieNode()
children = new TrieNode[26];
TrieNode root;
public Trie()
root = new TrieNode();
public void insert(String word)
TrieNode curr = root;
for (int i=0;i<word.length();i++)
char c = word.charAt(i);
int index = c - 'a';
if(curr.children[index]==null)//curr.children.get(c) == null
curr.children[index] = new TrieNode();
curr = curr.children[index]; //curr == curr.children.get(c)
curr.isWord = true;
public boolean search(String word)
TrieNode curr = root;
for (int i=0;i<word.length();i++)
char c = word.charAt(i);
int index = c - 'a';
if(curr.children[index]==null)
return false;
curr = curr.children[index];
return curr.isWord;
public boolean startsWith(String prefix)
TrieNode curr = root;
for (int i=0;i<prefix.length();i++)
char c = prefix.charAt(i);
int index = c - 'a';
if(curr.children[index]==null)
return false;
curr = curr.children[index];
return true;
TrieDemo.java
import java.util.Scanner;
public class TrieDemo
public static void main(String[] args)
Scanner cin = new Scanner(System.in);
Trie trie = new Trie();
String s;
while (true)
s = cin.nextLine();
if (s.equals("over"))
break;
else
String st[] = s.split(" ");
if(st[0].equals("insert"))
trie.insert(st[1]);
else if(st[0].equals("search"))
if (trie.search(st[1]))
System.out.println("true");
else
System.out.println("false");
else if (st[0].equals("startsWith"))
if (trie.startsWith(st[1]))
System.out.println("true");
else
System.out.println("false");
输入:
insert apple
search apple
search app
startsWith app
insert app
search app
输出:
true
false
true
true
以上是关于字典树——入门学习(java代码实现)的主要内容,如果未能解决你的问题,请参考以下文章