我想知道是否有可能修改三元搜索樹來檢查該單詞是否存在AND找到以該單詞開始的所有單詞(或以該單詞結束?)? 例如do
=>dog
dogs
等C#中的所有建議自動完成的三元搜索樹#
從這site是一個示例代碼。首先將所有單詞加載到三元樹,然後我們可以使用方法來檢查單詞是否存在。
public class TernaryTree
{
private Node m_root = null;
private void Add(string s, int pos, ref Node node)
{
if (node == null) { node = new Node(s[pos], false); }
if (s[pos] < node.m_char) { Add(s, pos, ref node.m_left); }
else if (s[pos] > node.m_char) { Add(s, pos, ref node.m_right); }
else
{
if (pos + 1 == s.Length) { node.m_wordEnd = true; }
else { Add(s, pos + 1, ref node.m_center); }
}
}
public void Add(string s)
{
if (s == null || s == "") throw new ArgumentException();
Add(s, 0, ref m_root);
}
public bool Contains(string s)
{
if (s == null || s == "") throw new ArgumentException();
int pos = 0;
Node node = m_root;
while (node != null)
{
int cmp = s[pos] - node.m_char;
if (s[pos] < node.m_char) { node = node.m_left; }
else if (s[pos] > node.m_char) { node = node.m_right; }
else
{
if (++pos == s.Length) return node.m_wordEnd;
node = node.m_center;
}
}
return false;
}
}
class Node
{
internal char m_char;
internal Node m_left, m_center, m_right;
internal bool m_wordEnd;
public Node(char ch, bool wordEnd)
{
m_char = ch;
m_wordEnd = wordEnd;
}
}
這讓我在我的腦海loome大:(
任何方式獲取的話可以是任何東西,但我與該級別的算法弱..
我希望,我不重複這個我覺得有任何問題。 任何建議,我會爲感激。