检查单词是否与搜索单词匹配的功能

问题描述

我有以下可行的方法,但想知道是否有更好的方法。更好的意思是更有效和或更紧凑。

功能检查一个Trie,以查看单词是否在Trie中。

bool check(const char *word)
{        
    int nodeIdx = hash(word);     
    if (nodeIdx < 0)return false;       

    nodeWords * searchNode;    
    searchNode = nodeArray[nodeIdx];  //nodeArray is global    
    bool whileFlag = true,returnFlag = false;
    
    do
    {
        if (strcmp(word,searchNode->word) == 0 ) 
        {
            whileFlag = false;
            returnFlag = true;
        }
        else if (strcmp(word,searchNode->word) < 0 )
        {            
            if(searchNode->left == NULL)
            {
                whileFlag = false;
            }else{
                searchNode = searchNode->left;
            }
        }else{               
            if(searchNode->right == NULL)
            {                
                whileFlag = false;
            }else{
                searchNode = searchNode->right;
            }
        }
    }while (whileFlag);    

    free(searchNode);    
    return returnFlag;
}

例如,我们可以这样重写函数

bool check(const char *word)
{   
    int nodeIdx = hash(word);   
    if (nodeIdx < 0)return false;    

    nodeWords * searchNode; 
    searchNode = nodeArray[nodeIdx];    
    bool returnFlag = false;    

    do
    {
        if (strcmp(word,searchNode->word) == 0 )returnFlag = true;
        else if (strcmp(word,searchNode->word) < 0 && searchNode->left  != NULL) searchNode = searchNode->left;
        else if (strcmp(word,searchNode->word) > 0 && searchNode->right != NULL) searchNode = searchNode->right;
    }while (searchNode->left != NULL || searchNode->right != NULL || strcmp(word,searchNode->word) == 0);    
    
    return returnFlag;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)