【发布时间】:2012-11-30 10:06:46
【问题描述】:
我最近做了一个 26array 并试图模拟一个字典。
我似乎无法弄清楚如何制作这个。我尝试过传入整数的链表而不是字符串。我当前的代码创建了 26 个节点(a-z),然后每个节点都有 26 个节点(a-z)。我想用整数实现一种方法,比如(1-26)。这些 int 节点将表示项目,而我要传入的 int 链表将包含一组我希望在树中表示的 int,类似于字符串。
示例:传入集合 {1, 6 , 8},而不是诸如“hello”之类的字符串
#include <iostream>
using namespace std;
class N26
{
private:
struct N26Node
{
bool isEnd;
struct N26Node *children[26];
}*head;
public:
N26();
~N26();
void insert(string word);
bool isExists(string word);
void printPath(char searchKey);
};
N26::N26()
{
head = new N26Node();
head->isEnd = false;
}
N26::~N26()
{
}
void N26::insert(string word)
{
N26Node *current = head;
for(int i = 0; i < word.length(); i++)
{
int letter = (int)word[i] - (int)'a';
if(current->children[letter] == NULL)
{
current->children[letter] = new N26Node();
}
current = current->children[letter];
}
current->isEnd = true;
}
/* Pre: A search key
* Post: True is the search key is found in the tree, otherwise false
* Purpose: To determine if a give data exists in the tree or not
******************************************************************************/
bool N26::isExists(string word)
{
N26Node *current = head;
for(int i=0; i<word.length(); i++)
{
if(current->children[((int)word[i]-(int)'a')] == NULL)
{
return false;
}
current = current->children[((int)word[i]-(int)'a')];
}
return current->isEnd;
}
【问题讨论】:
-
从您的描述中我不明白您要做什么。这个问题很难回答,因为 strong 的诱惑是讨论实现解决方案的更好方法,而不是在这里尝试使用您的代码。如果您为解决方案设置了这种特定的形式,最好继续摸索它,直到您对代码有特定的问题。
-
这是我试图构建的结构的图像。基本上每个节点都有一个计数器。最顶层的节点跟踪每个单个 int 在数据集中出现的次数。下一层代表所有可能的 2Item 集,第三层代表所有可能的 3Item 集。节点旁边的蓝色数字表示输入数据集后的计数器。
-
问题中的代码泄漏了它分配的所有内存,但这与手头的问题完全不同。
-
@user1898442:你为什么要跟踪每个 int 在数据集中出现的次数?除了Markov chains,我无法想象这种东西的用途。