2017-04-15 66 views
0

我想为我的树数据结构实现一个搜索功能。我很困惑如何正确地实现这一点,因为我现在认为我的逻辑似乎是正确的......尽管我仍然是这方面的初学者。如果有人可以看看我的功能,并建议在哪里改进,那将不胜感激。主要接受大型文件,然后在其中搜索单词以基本测试功能。现在它对于应该在特定对象中的单词返回false。我找到/添加功能无法正常工作

例如错误消息

Error: jean-pierre is not in the spellcheck and it should have been 

搜索功能:

//looks up the word in the SpellCheck object. If it is in the SpellCheck object,true is returned. 
//You can assume that the word will be all lower case. 
bool lookup(const string& word) const { 

    if (!root_) { 
      return false; 
    } 

    Node* curr = root_; 

    if (word[0] == '\0') { 
      return curr->isTerminal_ == true; 
    } 


    for (int i = 0; i < word.length(); i++) 
    { 
      int idx = curr->getIndex(word[i]); 

      if (idx < 0 || idx >= 26){ 
        return false; 
      } 
      // Search top level for node that 
    // matches first character in key 

      if (curr->children_[idx] == nullptr) { 
        return false; 
      } 
      curr = curr->children_[idx]; 

    } 
    return curr->isTerminal_ == true; 
} 

节点结构:

struct Node { 
      bool isTerminal_; 
      char ch_; 
      Node* children_[26]; 
      Node(char c = '\0') { 
        isTerminal_ = false; 
        ch_ = c; 
        for (int i = 0; i < 26; i++) { 
          children_[i] = nullptr; 
        } 
      } 
      //given lower case alphabetic charachters ch, returns 
      //the associated index 'a' --> 0, 'b' --> 1...'z' --> 25 
      int getIndex(char ch) { 
        return ch - 'a'; 
      } 
    }; 
    Node* root_; 
+0

您的查找方法看起来还好。请提供您的插入功能 –

+0

插入功能在测试时正常工作。 – user7795742

+0

然后用放置断点调试你的代码。 –

回答

0

您有亩在你的实现中存在一些错误。

您的addWord功能不正确。 这一次应该会更好:

void addWord(const string& newWord, int currChar, Node* rt) 
{ 
    //check if currChar index is still in newWord 
    if (currChar < newWord.length()) { 
     //find index of currChar 
     char currLetter = newWord[currChar]; 
     int idx = rt->getIndex(currLetter); 

     //if no letter at that index create a new node 
     if (!rt->children_[idx]) 
      //make a new node 
      rt->children_[idx] = new Node(currLetter); 
     //continue to add 
     addWord(newWord, currChar + 1, rt->children_[idx]); 
    } 
    else 
     rt->isTerminal_ = true; //last char 
} 

你完全错过了其他的bug:"jean-pierre"包含非A-Z字:)和您的getIndex将失败,这不是[a-z]范围内的任何字符。

其他点:

  • 没有硬编码值就像26,因为如果你需要从[a-z]代码更新 范围的其他地方将静默失败。使用assert检查输入假设。

事情是这样的:

int getIndex(char ch) 
{ 
    assert(ch >= 'a' && ch <= 'z'); 
    return ch == '-' ? 26 : ch - 'a'; 
}