前缀树
package cn.hq;
class Node {
boolean isEnd = false;
Node[] next = new Node[26];
public void setIsEnd () {
this.isEnd = true;
}
}
public class MyTree {
Node root;
public MyTree() {
root = new Node();
}
public void insert(String string) {
char[] str = string.toCharArray();
Node node = root;
for (int i = 0; i < str.length; i++) {
int temp = str[i] - 'a';
if (node.next[temp] == null)
node.next[temp] = new Node();
node = node.next[temp];
}
node.setIsEnd();
}
public boolean search(String string) {
char[] str=string.toCharArray();
Node node=root;
for(int i=0;i<str.length;i++){
int temp=str[i]-'a';
if(node.next[temp]==null) return false;
node=node.next[temp];
}
return node.isEnd;
}
public boolean startsWith(String string) {
char[] str = string.toCharArray();
Node node = root;
for (int i = 0; i < str.length; i++) {
int temp = str[i] - 'a';
if (node.next[temp] == null) return false;
node = node.next[temp];
}
return true;
}
public static void main(String[] args) {
MyTree tree=new MyTree();
tree.insert("apple");
System.out.println(tree.search("apple"));
System.out.println(tree.search("app"));
tree.startsWith("app");
tree.insert("app");
System.out.println(tree.search("app"));
}
}