您的位置:首页 > 其它

LeetCode 208. Implement Trie (Prefix Tree)(前缀树)

2016-05-04 10:11 204 查看
原题网址:https://leetcode.com/problems/implement-trie-prefix-tree/

Implement a trie with
insert
,
search
,
and
startsWith
methods.

Note:

You may assume that all inputs are consist of lowercase letters
a-z
.
方法:使用数组实现下一节点的指向。

class TrieNode {
// Initialize your data structure here.
boolean isWord;
TrieNode[] nexts = new TrieNode[26];
public TrieNode() {
}
TrieNode append(int id) {
if (nexts[id] != null) return nexts[id];
nexts[id] = new TrieNode();
return nexts[id];
}
}

public class Trie {
private TrieNode root;

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

// Inserts a word into the trie.
public void insert(String word) {
TrieNode node = root;
char[] wa = word.toCharArray();
for(int i=0; i<wa.length; i++) node = node.append(wa[i]-'a');
node.isWord = true;
}

// Returns if the word is in the trie.
public boolean search(String word) {
if (word == null) return root.isWord;
TrieNode node =root;
char[] wa = word.toCharArray();
for(int i=0; i<wa.length; i++) {
if (node.nexts[wa[i]-'a'] == null) return false;
node = node.nexts[wa[i]-'a'];
}
return node.isWord;
}

// Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if (prefix == null) return root.isWord;
TrieNode node =root;
char[] pa = prefix.toCharArray();
for(int i=0; i<pa.length; i++) {
if (node.nexts[pa[i]-'a'] == null) return false;
node = node.nexts[pa[i]-'a'];
}
return true;
}
}

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