題目:
實現一個 Trie (前綴樹),包含 insert
, search
, 和 startsWith
這三個操作。
示例:
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
說明:
- 你可以假設所有的輸入都是由小寫字母
a-z
構成的。 - 保證所有輸入均爲非空字符串。
一開始沒聽說過什麼是前綴樹,覺得這題好簡單,直接使用string的函數實現了,發現對於大量的字符串處理,string的封裝函數處理性能完全不夠,後來百度才知道原來前綴樹是一個名詞,詳細解釋請見鏈接:https://www.cnblogs.com/luosongchao/p/3239521.html#undefined這個裏面解釋的非常清楚。
看完前綴樹的解釋,然後又看了LeetCode上大家的評論,給出C#實現的前綴樹。
執行用時 : 344 ms, 在Implement Trie (Prefix Tree)的C#提交中擊敗了67.74% 的用戶
內存消耗 : 46.8 MB, 在Implement Trie (Prefix Tree)的C#提交中擊敗了22.22% 的用戶
class Trie
{
private class Node
{
public Node[] children;
public bool isEnd = false;
public Node()
{
children = new Node[26];
isEnd = false;
}
}
private Node rootNode = null;
/** Initialize your data structure here. */
public Trie()
{
rootNode = new Node();
}
/** Inserts a word into the trie. */
public void Insert(String word)
{
Node currNode = rootNode;
for (int i = 0; i < word.Length; i++)
{
if (currNode.children[word[i] - 'a'] == null)
{
currNode.children[word[i] - 'a'] = new Node();
}
currNode = currNode.children[word[i] - 'a'];
}
currNode.isEnd = true;
}
/** Returns if the word is in the trie. */
public bool Search(String word)
{
Node currNode = rootNode;
for (int i = 0; i < word.Length; i++)
{
if (currNode.children[word[i] - 'a'] == null)
{
return false;
}
currNode = currNode.children[word[i] - 'a'];
}
return currNode.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public bool StartsWith(String prefix)
{
Node currNode = rootNode;
for (int i = 0; i < prefix.Length; i++)
{
if (currNode.children[prefix[i] - 'a'] == null)
{
return false;
}
currNode = currNode.children[prefix[i] - 'a'];
}
return true;
}
}