您的位置:首页 > 其它

[leetcode刷题笔记]Implement Trie (Prefix Tree)

2015-07-14 19:53 295 查看
题目链接

一A,开森~

ac代码:

class TrieNode {
// Initialize your data structure here.
char content;
boolean isWord;
int count;
LinkedList<TrieNode> childList;

public TrieNode(char c) {
content = c;
isWord = false;
count = 0;
childList = new LinkedList<TrieNode>();
}
public TrieNode() {
content = ' ';
isWord = false;
count = 0;
childList = new LinkedList<TrieNode>();
}

public TrieNode findChildC(char c){
if(childList != null){
for(TrieNode eachChild:childList){
if(eachChild.content == c)
return eachChild;
}
}
return null;
}
}

public class Trie {
private TrieNode root;

public Trie() {
root = new TrieNode();

}

// Inserts a word into the trie.
public void insert(String word) {
//if already has this word
if(search(word) == true)
return;

TrieNode current = root;
for(int i = 0;i < word.length();i++){
TrieNode child = current.findChildC(word.charAt(i));
if(child == null){
TrieNode temp = new TrieNode(word.charAt(i));
current.childList.add(temp);
current = temp;
}else{
current = child;
}
current.count++;
}
current.isWord = true;
}

// Returns if the word is in the trie.
public boolean search(String word) {
TrieNode current = root;
for(int i = 0;i < word.length();i++){
TrieNode child = current.findChildC(word.charAt(i));
if(child == null)
return false;
else{
current = child;
continue;
}
}
if(current.isWord)
return true;
return false;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
TrieNode current = root;
for(int i = 0;i < prefix.length();i++){
TrieNode child = current.findChildC(prefix.charAt(i));
if(child == null)
return false;
else{
current = child;
continue;
}
}
return true;
}
}

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