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