2015-12-10 30 views
1

什麼是搜索功能特里數據結構implementaion的bug

search_word(); 

的錯誤,這是實現使用效率的時間複雜度爲特里或沒有像插入/搜查行動。 考慮一個1500字符的字符串,在不到2秒的時間內執行插入/搜索操作,是否可以通過?

class Trie 
{ 
private: 
    struct node 
    { 
     bool isWord; 
     node* child[26]; 
     node() 
     { 
      for(int i = 0;i < 26;i++) 
       child[i] = NULL; 
      isWord = false; 
     } 
    }; 

    void insert_word(int index, node* vertex, int i, string s) 
    { 
     if(index == SZ) 
     { 
      vertex -> isWord = true; 
      return; 
     } 
     int c = s[index] - 'a'; 
     if(vertex -> child[c] == NULL) 
      vertex -> child[c] = new node; 

     insert_word(index + 1, vertex -> child[c], c, s); 

    } 
    bool search_word(int index, node* vertex, int i, string s) 
    { 
     if(index == SZ && vertex -> isWord == true) 
      return true; 
     if(index == SZ && vertex -> isWord == false) 
      return false; 

     int c = s[index] - 'a'; 

     if(vertex -> child[c] == NULL) 
      return false; 
     else 
      return search_word(index + 1, vertex -> child[c], c, s); 
    } 
public: 
    int SZ; 
    node* root; 
    Trie() 
    { 
     root = new node; 
    } 
    void insert_word(string s) 
    { 
     SZ = s.size(); 
     insert_word(0, root, s[0] - 'a', s); 
    } 
    bool search_word(string s) 
    { 
     SZ = s.size(); 
     return search_word(0, root, s[0] - 'a', s); 
    } 

}; 

更新:發現錯誤和代碼必須正常工作。

回答

1

很好,我已經找到了錯誤,它是在代碼塊

if(index == (SZ - 1)) 
    { 
     vertex -> isWord = true; 
     return; 
    } 

指數必須檢查==與大小本身沒有大小-1爲什麼..? ex:字符串ab如果我們現在正在處理字母b is it == to size - 1表示字符串中的最後一個字符代碼將它的根標記爲字的結尾而不是與字符b相關的節點,因爲它從來沒有一直在

search_word() 

大小創建 通過它來編輯它應該工作正常也大小 - 1必須被編輯過

注:我會更新這個問題本身有固定的代碼。