【问题标题】:What is happening in the following code of a trie以下 trie 代码中发生了什么
【发布时间】: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 &gt;= 0 &amp;&amp; index &lt; 26) 以确保它在a-z 之间,因为{} 也会产生&gt;= 0

标签: c++ algorithm trie


【解决方案1】:

int index = currentChar - 'a'; 行处,currentChar(无论它是什么)将减去具有ASCII 值 97 的“a”字符。
在这种情况下,您有两个条件:

  1. 首先如果currentChar在a-z之间,index的结果将永远是&gt;= 0

  2. 否则currentChar不在a-z之间,因为index将是负数,currentChar不能在A-Z之间,因为tolower()函数。

您可以参考此link 以了解有关ASCII 值的更多信息

您还需要更新条件 assert(index &gt;= 0 &amp;&amp; index &lt; 26) 因为 { ,} ,|和 ~ 将使索引 >=0

【讨论】:

    【解决方案2】:

    人们容易忘记的东西——一个字符是一个包含 ascii 值的字节。

    所以 'a' 在 ascii 表中是 97(我认为),所以一切都在完成 - 是 currentChar-97。

    请按照http://www.asciitable.com 获取实际值。

    但永远记住 - 一个字符是一个字节,你可以经常使用这个事实!
    我用它来跳过指针中的内存地址(例如:

    void* a = (void*)((char*)arr+2);
    

    此代码将返回 arr+ 两个字节的内存,同时忽略 arr 中保存的类型)

    请注意 - |'a'-'A'| = |'A'-'a'| , 但一个是负的, 而另一个是正的

    【讨论】:

      【解决方案3】:

      int index = currentChar - 'a';这是为了检查字符,因为用户可以输入不在 a 到 z 之间的字符。

      【讨论】:

        【解决方案4】:

        它将为您提供字母表中的字母位置,将a 视为位置0。这里a被转换成它的ASCII码,减去a-z这个字母变得更容易处理了。

        【讨论】:

          最近更新 更多