From 64d073d19405ebb152290312305ff8289f361709 Mon Sep 17 00:00:00 2001 From: yanyiwu Date: Sat, 27 Jun 2015 11:39:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81insertUserWord=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Trie.hpp | 21 ++++++++++++++++----- test/unittest/TApplication.cpp | 8 ++++---- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Trie.hpp b/src/Trie.hpp index cfc20e3..eb20b36 100644 --- a/src/Trie.hpp +++ b/src/Trie.hpp @@ -155,18 +155,24 @@ class Trie { return !res.empty(); } void insertNode(const Unicode& key, const DictUnit* ptValue) { - insertNode_(key, ptValue); + TrieNode* newAddedNode = insertNode_(key, ptValue); + if (newAddedNode) { + build_(newAddedNode); + } } private: void build_() { - queue que; assert(root_->ptValue == NULL); assert(root_->next); root_->fail = NULL; for(TrieNode::NextMap::iterator iter = root_->next->begin(); iter != root_->next->end(); iter++) { - iter->second->fail = root_; - que.push(iter->second); + build_(iter->second); } + } + void build_(TrieNode* node) { + node->fail = root_; + queue que; + que.push(node); TrieNode* back = NULL; TrieNode::NextMap::iterator backiter; while(!que.empty()) { @@ -202,8 +208,9 @@ class Trie { insertNode_(keys[i], valuePointers[i]); } } - void insertNode_(const Unicode& key, const DictUnit* ptValue) { + TrieNode* insertNode_(const Unicode& key, const DictUnit* ptValue) { TrieNode* ptNode = root_; + TrieNode* newAddedNode = NULL; TrieNode::NextMap::const_iterator kmIter; @@ -217,6 +224,9 @@ class Trie { nextNode->next = NULL; nextNode->ptValue = NULL; + if(newAddedNode == NULL) { + newAddedNode = nextNode; + } (*ptNode->next)[*citer] = nextNode; ptNode = nextNode; } else { @@ -224,6 +234,7 @@ class Trie { } } ptNode->ptValue = ptValue; + return newAddedNode; } void deleteNode_(TrieNode* node) { if(!node) { diff --git a/test/unittest/TApplication.cpp b/test/unittest/TApplication.cpp index bfb888a..7aef022 100644 --- a/test/unittest/TApplication.cpp +++ b/test/unittest/TApplication.cpp @@ -64,9 +64,9 @@ TEST(ApplicationTest, InsertUserWord) { result << words; ASSERT_EQ("[\"男默\", \"女泪\"]", result); - //ASSERT_TRUE(app.insertUserWord("男默女泪")); + ASSERT_TRUE(app.insertUserWord("男默女泪")); - //app.cut("男默女泪", words); - //result << words; - //ASSERT_EQ("[\"男默女泪\"]", result); + app.cut("男默女泪", words); + result << words; + ASSERT_EQ("[\"男默女泪\"]", result); }