【发布时间】:2014-05-13 01:02:14
【问题描述】:
我正在查看 Trie 的 example,但我很难理解以下代码
void Trie::addWord(string word)
{
Node * currentNode = root;
for (int i = 0; i < word.size(); ++i)
{
char currentChar = tolower(word.at(i));
int index = currentChar - 'a';
assert(index >= 0); // Makes sure the character is between a-z
if (currentNode->children[index] != NULL)
{
// check if the current node has the current character as one of its decendants
currentNode = currentNode->children[index];
}
else
{
// the current node doesn't have the current character as one of its decendants
Node * newNode = new Node(currentChar);
currentNode->children[index] = newNode;
currentNode = newNode;
}
if (i == word.size() - 1)
{
// the last character of the word has been reached
currentNode->end = true;
}
}
}
我的问题是为什么这里要减去a
int index = currentChar - 'a';
【问题讨论】:
-
它应该是
assert(index >= 0 && index < 26)以确保它在a-z之间,因为{和}也会产生>= 0。