【发布时间】:2020-03-21 19:54:30
【问题描述】:
#include<iostream>
using namespace std;
class trieNode{
public:
int data;
bool isTerminal;
trieNode ** children;
trieNode(int data){
this->data = data;
children = new trieNode*[26];
for(int i=0;i<26;i++){
children[i] = NULL;
}
isTerminal = false;
}
};
class Pair{
public:
bool exist;
trieNode* address;
Pair(){
exist = false;
address = NULL;
}
};
class Trie{
public:
trieNode *root;
Trie(){
root = new trieNode('\0');
}
// for programmer
private:
void insert(trieNode* root,string word){
//base case
if(word.size() == 0){
root->isTerminal = true;
return ;
}
// small calculation
int index = word[0] - 'a';
trieNode *child;
if(root->children[index] != NULL){
child = root->children[index];
}
else{
child = new trieNode(word[0]);
root->children[index] = child;
}
// recursion
insert(child,word.substr(1));
}
// for user
public:
void insertWord(string word){
insert(root,word);
}
// for programmer
private:
void deleteWord(trieNode* root, string word){
if(word.size() == 0){
root->isTerminal = false;
return;
}
int index = word[0] - 'a';
trieNode *child;
if(root->children[index] != NULL){
child = root->children[index];
}
else{
return;
}
deleteWord(child,word.substr(1));
if(child->isTerminal == false){
for(int i=0;i<26;i++){
if(child->children[i] != NULL)
return;
}
delete child;
root->children[index] = NULL;
}
}
// delete word
//for user
public:
void deleteWord(string word){
deleteWord(root,word);
}
// search a sting in trie
//function for programmer
// i used a pair class as return type brcause i want to return if word exists then return it's
address too
// i.e return a bool = true and adress where the word ends
private:
Pair find(trieNode *root, string word){
Pair p;
if(word.size() == 0){
Pair p;
p.address = root;
if(root->isTerminal == true)
p.exist = true;
else
p.exist = false;
return p;
}
trieNode *child;
int index = word[0]-'a';
if(root->children[index] == NULL){
Pair p;
p.address = root;
p.exist = false;
return p;
}
else{
child = root->children[index];
p = find(child, word.substr(1));
}
}
// search a string in the trie
// function for user
public:
Pair findstr(string word){
Pair p;
p = find(root,word);
return p;
}
};
int main(){
Trie t;
t.insertWord("sucess");
t.insertWord("s");
t.insertWord("a");
Pair p;
p = t.findstr("sucess");
cout<< p.address->data <<" "<< p.exist<<endl;
p = t.findstr("s");
cout<< p.address->data <<" "<< p.exist<<endl;
p = t.findstr("a");
cout<< p.address->data <<" "<< p.exist;
我正在使用 pair 类来实现一个名为 findstr 的函数,该函数在 trie 中找到一个单词并返回 2 个东西一个 bool 和该单词的最后一个 trieNode 的地址,因为我使用了一个 pair 类,在这段代码中它应该十六进制返回地址,所有三个都为真,但我只看到垃圾值
}
【问题讨论】:
-
现在是使用调试器并逐步执行程序的时候了。调试器允许您一次运行您的程序,您可以在其中观察变量、观察程序的流程等。