支持insertUserWord接口

This commit is contained in:
yanyiwu 2015-06-27 11:39:43 +08:00
parent c5f7d4d670
commit 64d073d194
2 changed files with 20 additions and 9 deletions

View File

@ -155,18 +155,24 @@ class Trie {
return !res.empty(); return !res.empty();
} }
void insertNode(const Unicode& key, const DictUnit* ptValue) { void insertNode(const Unicode& key, const DictUnit* ptValue) {
insertNode_(key, ptValue); TrieNode* newAddedNode = insertNode_(key, ptValue);
if (newAddedNode) {
build_(newAddedNode);
}
} }
private: private:
void build_() { void build_() {
queue<TrieNode*> que;
assert(root_->ptValue == NULL); assert(root_->ptValue == NULL);
assert(root_->next); assert(root_->next);
root_->fail = NULL; root_->fail = NULL;
for(TrieNode::NextMap::iterator iter = root_->next->begin(); iter != root_->next->end(); iter++) { for(TrieNode::NextMap::iterator iter = root_->next->begin(); iter != root_->next->end(); iter++) {
iter->second->fail = root_; build_(iter->second);
que.push(iter->second);
} }
}
void build_(TrieNode* node) {
node->fail = root_;
queue<TrieNode*> que;
que.push(node);
TrieNode* back = NULL; TrieNode* back = NULL;
TrieNode::NextMap::iterator backiter; TrieNode::NextMap::iterator backiter;
while(!que.empty()) { while(!que.empty()) {
@ -202,8 +208,9 @@ class Trie {
insertNode_(keys[i], valuePointers[i]); 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* ptNode = root_;
TrieNode* newAddedNode = NULL;
TrieNode::NextMap::const_iterator kmIter; TrieNode::NextMap::const_iterator kmIter;
@ -217,6 +224,9 @@ class Trie {
nextNode->next = NULL; nextNode->next = NULL;
nextNode->ptValue = NULL; nextNode->ptValue = NULL;
if(newAddedNode == NULL) {
newAddedNode = nextNode;
}
(*ptNode->next)[*citer] = nextNode; (*ptNode->next)[*citer] = nextNode;
ptNode = nextNode; ptNode = nextNode;
} else { } else {
@ -224,6 +234,7 @@ class Trie {
} }
} }
ptNode->ptValue = ptValue; ptNode->ptValue = ptValue;
return newAddedNode;
} }
void deleteNode_(TrieNode* node) { void deleteNode_(TrieNode* node) {
if(!node) { if(!node) {

View File

@ -64,9 +64,9 @@ TEST(ApplicationTest, InsertUserWord) {
result << words; result << words;
ASSERT_EQ("[\"男默\", \"女泪\"]", result); ASSERT_EQ("[\"男默\", \"女泪\"]", result);
//ASSERT_TRUE(app.insertUserWord("男默女泪")); ASSERT_TRUE(app.insertUserWord("男默女泪"));
//app.cut("男默女泪", words); app.cut("男默女泪", words);
//result << words; result << words;
//ASSERT_EQ("[\"男默女泪\"]", result); ASSERT_EQ("[\"男默女泪\"]", result);
} }