void Trie::AddWord(string s) { TrieNode* current = root; if(s.length() == 0) { current->Mark(); // recognize empty word return; } unsigned long len = s.length(); for (int i=0; i<len-1; i++) { TrieNode *child = current->FindChild(s[i]); if(child != NULL) { current = child; } else { TrieNode* tmp = new TrieNode(s[i], false); tmp->Set(s[i]); current->AddChild(tmp); current = tmp; } if (s[i+1]=='/') { current->Mark(); break; } if ( i == len - 2 ) current->Mark(); } }
bool Trie::SearchWord(string s) { TrieNode* current = root; unsigned long len = s.length(); for (int i=0; i<len; i++) { current = current->FindChild(s[i]); if(current == NULL) return false; } if(current->IsFinal()) return true; return false; }
// Inserts a word into the trie. void insert(string s) { TrieNode *prev = nullptr; TrieNode *curr = m_root; // We check the characters of s one by one. Note that // we also add the NULL terminator to the Trie which // indicates the end of a word. for (int i = 0; i <= s.length(); i++) { prev = curr; curr = prev->FindChild(s[i]); // Can't find a TrieNode with the character s[i], // so create a new one and add it to the children // list of prev. if (curr == nullptr) { curr = new TrieNode(s[i]); prev->AddChild(curr); } } }
void findWordsStartFromOneCell( vector<vector<char>>& board, int m, int n, int i, int j, TrieNode* currNode, string& word, vector<string>& foundWords) { TrieNode *childNode = currNode->FindChild(board[i][j]); if (childNode == nullptr) { return; } word.push_back(board[i][j]); board[i][j] = 'X'; TrieNode *wordEndNode = childNode->FindChild(0); if ((wordEndNode != nullptr) && (wordEndNode->GetChar() != 'X')) { foundWords.push_back(word); wordEndNode->SetChar('X'); } if ((i > 0) && (board[i - 1][j] != 'X')) { findWordsStartFromOneCell( board, m, n, i - 1, j, childNode, word, foundWords); } if ((i < m - 1) && (board[i + 1][j] != 'X')) { findWordsStartFromOneCell( board, m, n, i + 1, j, childNode, word, foundWords); } if ((j > 0) && (board[i][j - 1] != 'X')) { findWordsStartFromOneCell( board, m, n, i, j - 1, childNode, word, foundWords); } if ((j < n - 1) && (board[i][j + 1] != 'X')) { findWordsStartFromOneCell( board, m, n, i, j + 1, childNode, word, foundWords); } board[i][j] = word.back(); word.pop_back(); }