您的位置:首页 > 其它

leetcode 208. Implement Trie (Prefix Tree)

2017-04-06 10:38 274 查看
Implement a trie with 
insert
search
,
and 
startsWith
 methods.

Note:

You may assume that all inputs are consist of lowercase letters 
a-z
.

Subscribe to see which companies asked this question.

public class Trie {
private class node{
boolean mark;
char val;
node(char mchar){
val=mchar;
}
node[] children=new node[26];
}
private node root;
public Trie() {
root = new node(' ');
}

public void insert(String word) {
node temp=root;
for(int i=0;i<word.length();i++){
char mchar=word.charAt(i);
if(temp.children[mchar-'a']==null){
temp.children[mchar-'a']=new node(mchar);
}
temp=temp.children[mchar-'a'];
}
temp.mark=true;
}

public boolean search(String word) {
node temp=root;
for(int i=0;i<word.length();i++){
char mchar=word.charAt(i);
if(temp.children[mchar-'a']==null){
return false;
}
temp=temp.children[mchar-'a'];
}
return  temp.mark;
}

public boolean startsWith(String prefix) {
node temp=root;
for(int i=0;i<prefix.length();i++){
char mchar=prefix.charAt(i);
if(temp.children[mchar-'a']==null){
return false;
}
temp=temp.children[mchar-'a'];
}
return  true;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: