我正在浏览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';
最佳答案
在int index = currentChar - 'a';
行处currentChar
(无论它是什么)都将被具有ASCII
值97的'a'字符减去。
在这种情况下,您有两个条件:
currentChar
在a-z之间,则index
的结果将始终为>= 0
。 currentChar
不在a-z之间,因为index
将为负数,由于A-Z
函数,currentChar不能在tolower()
之间。 您可以引用此link,以进一步了解
ASCII
值另外,您还需要更新条件
assert(index >= 0 && index < 26)
,因为{,},|和〜将使索引> = 0关于c++ - 下面的trie代码中发生了什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22799711/