208 Implement Trie (Prefix Tree) 實(shí)現(xiàn) Trie (前綴樹)
Description:
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
題目描述:
實(shí)現(xiàn)一個(gè) Trie (前綴樹),包含 insert, search, 和 startsWith 這三個(gè)操作。
示例 :
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // 返回 true
trie.search("app"); // 返回 false
trie.startsWith("app"); // 返回 true
trie.insert("app");
trie.search("app"); // 返回 true
說(shuō)明:
你可以假設(shè)所有的輸入都是由小寫字母 a-z 構(gòu)成的。
保證所有輸入均為非空字符串。
思路:
用一個(gè)變量 is_word記錄, 方便查找
用一個(gè)字符數(shù)組記錄出現(xiàn)過(guò)的字符
查詢單詞或者前綴時(shí)沒(méi)有這個(gè)字符就返回 false
查詢返回 is_word
前綴返回 true
Trie就是維護(hù)公共前綴的樹
插入時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(n), 其中 n為所查找的字符串的長(zhǎng)度
查找時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1), 其中 n為所查找的字符串的長(zhǎng)度
前綴查找時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1), 其中 n為所查找的字符串的長(zhǎng)度
代碼:
C++:
class Trie
{
private:
Trie *child[26];
bool is_word;
public:
/** Initialize your data structure here. */
Trie()
{
is_word = false;
for (int i = 0; i < 26; i++) child[i] = nullptr;
}
/** Inserts a word into the trie. */
void insert(string word)
{
Trie *cur = this;
for (auto c : word)
{
if (!cur -> child[c - 'a']) cur -> child[c - 'a'] = new Trie();
cur = cur -> child[c - 'a'];
}
cur -> is_word = true;
}
/** Returns if the word is in the trie. */
bool search(string word)
{
Trie *cur = this;
for (auto c : word)
{
if (!cur -> child[c - 'a']) return false;
cur = cur -> child[c - 'a'];
}
return cur -> is_word;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix)
{
Trie *cur = this;
for (auto c : prefix)
{
if (!cur -> child[c - 'a']) return false;
cur = cur -> child[c - 'a'];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
Java:
class Trie {
private class TrieNode {
private boolean isWord;
private TrieNode[] child;
public TrieNode() {
isWord = false;
child = new TrieNode[26];
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
if (cur.child[c - 'a'] == null) cur.child[c - 'a'] = new TrieNode();
cur = cur.child[c - 'a'];
}
cur.isWord = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode cur = root;
for (char c : word.toCharArray()) {
if (cur.child[c - 'a'] == null) return false;
cur = cur.child[c - 'a'];
}
return cur.isWord;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode cur = root;
for (char c : prefix.toCharArray()) {
if (cur.child[c - 'a'] == null) return false;
cur = cur.child[c - 'a'];
}
return true;
}
}
/**
* Your Trie object will be instantiated and called as such:
* Trie obj = new Trie();
* obj.insert(word);
* boolean param_2 = obj.search(word);
* boolean param_3 = obj.startsWith(prefix);
*/
Python:
class Trie:
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
"""
node = self.root
for c in word:
if c not in node.keys():
node[c] = {}
node = node[c]
node['is_word'] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the trie.
"""
node = self.root
for c in word:
if c not in node.keys():
return False
node = node[c]
return 'is_word' in node.keys()
def startsWith(self, prefix: str) -> bool:
"""
Returns if there is any word in the trie that starts with the given prefix.
"""
node = self.root
for c in prefix:
if c not in node.keys():
return False
node = node[c]
return True
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)