您的位置:首页 > 其它

[LeetCode]Implement Trie (Prefix Tree)

2015-12-06 12:36 393 查看
class TrieNode {
// Initialize your data structure here.
TrieNode[] child;
boolean isWord;
public TrieNode() {
child = new TrieNode[26];
isWord = false;
}
}

public class Trie {
private TrieNode root;

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

// Inserts a word into the trie.
public void insert(String word) {
insert(word, root);
}
public void insert(String word, TrieNode root) {
if (word.length() == 0) {
root.isWord = true;
return;
}
char ch = word.charAt(0);
if (root.child[ch - 'a'] == null) {
root.child[ch - 'a'] = new TrieNode();
}
insert(word.substring(1), root.child[ch - 'a']);
}

// Returns if the word is in the trie.
public boolean search(String word) {
return search(word, root);
}
public boolean search(String word, TrieNode root) {
if (word.length() == 0) {
return root.isWord;
}
char ch = word.charAt(0);
if (root.child[ch - 'a'] == null) {
return false;
} else {
return search(word.substring(1), root.child[ch - 'a']);
}
}

// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
return startsWith(prefix, root);
}
public boolean startsWith(String prefix, TrieNode root) {
if (prefix.length() == 0) {
return true;
}
char ch = prefix.charAt(0);
if (root.child[ch - 'a'] == null) {
return false;
} else {
return startsWith(prefix.substring(1), root.child[ch - 'a']);
}
}
}

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