我正在尝试使用Linkedlist和Arrays在C ++中实现Trie,但它有一些我无法追踪的逻辑错误。从程序中,我希望将字符串作为输入用于插入和结束输入模式,我提供了#'#'字符。 它转移到搜索模式,但每个查询都打印"未找到"。 我正在使用编译器VC12 - Visual Studio 2013社区。 p>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
enum state{
acceptable, na
};
class TrieNode{
void setNULL(){
for (int i = 0; i < 26; i++)
{
next[i] = NULL;
}
}
public:
state s;
TrieNode *next[26];
TrieNode(){
setNULL();
s = na;
}
TrieNode(state s){
this->s = s;
setNULL();
}
TrieNode *&goNext(char ch){
ch = tolower(ch);
return next[ch - 'a'];
}
};
class Trie{
TrieNode *head[26];
void setNULL(){
for (int i = 0; i < 26; i++)
{
head[i] = NULL;
}
}
public:
Trie(){
setNULL();
}
void insert(string &s){
TrieNode *ptr = head[s[0] - 'a'];
if (ptr == NULL){
ptr = new TrieNode();
}
int i = 1;
while (i < s.length())
{
if (ptr->goNext(s[i]) == NULL){
ptr->goNext(s[i]) = new TrieNode();
}
ptr = ptr->goNext(s[i]);
i++;
}
ptr->s = acceptable;
}
bool search(string &s){
TrieNode *ptr = head[s[0] - 'a'];
int i = 1;
bool found = true;
while (i < s.length() && found){
if (ptr == NULL || ptr->goNext(s[i]) == NULL)
found = false;
else
ptr = ptr->goNext(s[i]);
}
if (found == true)
return true;
return false;
}
};
int main(){
Trie t;
string s;
while (cin >> s, s != "#"){
t.insert(s);
}
cout << "Search mode\n";
while (cin >> s, s != "#"){
if (t.search(s))
cout << "Found\n";
else
cout << "Not found\n";
}
/*
Sample Input:
hello
how
are
you
#
hello
*/
return 0;
}
答案 0 :(得分:0)
修改后的最终计划。谢谢大家的帮助。
#include <iostream>
#include <string>
#include <cctype>
#include <iomanip>
using namespace std;
enum state{
acceptable, na
};
class TrieNode{
void setNULL(){
for (int i = 0; i < 26; i++)
{
next[i] = NULL;
}
}
public:
state s;
TrieNode *next[26];
TrieNode(){
setNULL();
s = na;
}
TrieNode(state s){
this->s = s;
setNULL();
}
TrieNode *&goNext(char ch){
ch = tolower(ch);
return next[ch - 'a'];
}
};
class Trie{
TrieNode *head[26];
void setNULL(){
for (int i = 0; i < 26; i++)
{
head[i] = NULL;
}
}
public:
Trie(){
setNULL();
}
void insert(string &s){
TrieNode *ptr = head[s[0] - 'a'];
if (ptr == NULL){
ptr = new TrieNode();
head[s[0] - 'a'] = ptr;
}
int i = 1;
while (i < s.length())
{
if (ptr->goNext(s[i]) == NULL){
ptr->goNext(s[i]) = new TrieNode();
}
ptr = ptr->goNext(s[i]);
i++;
}
ptr->s = acceptable;
}
bool search(string &s){
TrieNode *ptr = head[s[0] - 'a'];
if (ptr == NULL)
return false;
int i = 1;
bool found = true;
while (i < s.length() && found){
if (ptr == NULL || ptr->goNext(s[i]) == NULL)
found = false;
else
ptr = ptr->goNext(s[i]);
i++;
}
if (ptr->s == acceptable)
return found;
return false;
}
};
int main(){
Trie t;
cout << "Note : Only small characters are acceptable\n";
string s;
while (cin >> s, s != "#"){
t.insert(s);
}
cout << "Search mode\n";
while (cin >> s, s != "#"){
if (t.search(s))
cout << setw(20) << "Found\n";
else
cout << setw(20) << "Not found\n";
}
/*
Sample Input:
hello
how
are
you
#
hello
*/
return 0;
}