您的位置:首页 > 其它

leetcode Implement Trie (Prefix Tree)

2015-08-29 14:34 381 查看
题目链接

思路:



class TrieNode {
// Initialize your data structure here.
TrieNode charecters[];
boolean end;
public TrieNode() {
charecters=new TrieNode[26];
end=false;
}
}

public class Trie {
private TrieNode root;

public Trie() {
root = new TrieNode();
root.charecters=new TrieNode[26];
}

// Inserts a word into the trie.
public void insert(String word) {
int n=word.length();
TrieNode temp=root;
for(int i=0;i<n;i++)
{

if(temp.charecters[word.charAt(i)-'a']==null)
{
temp.charecters[word.charAt(i)-'a']=new TrieNode();
}
temp=temp.charecters[word.charAt(i)-'a'];

}
temp.end=true;
}

// Returns if the word is in the trie.
public boolean search(String word) {
int n=word.length();
TrieNode temp=root;
for(int i=0;i<n;i++)
{

if(temp.charecters[word.charAt(i)-'a']==null)
{
return false;
}
temp=temp.charecters[word.charAt(i)-'a'];

}
return temp.end;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
int n=prefix.length();
TrieNode temp=root;
for(int i=0;i<n;i++)
{

if(temp.charecters[prefix.charAt(i)-'a']==null)
{
return false;
}
temp=temp.charecters[prefix.charAt(i)-'a'];

}
if(temp.end)
{
return true;
}
for(int i=0;i<26;i++)
{
if(temp.charecters[i]!=null)
{
return true;
}
}

return false;
}
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: