字典樹模板(陣列實現和指標實現)
阿新 • • 發佈:2018-12-31
///這裡以輸入字串後,查詢字串出現的次數為例
#include<bits/stdc++.h>
#define MAX 26
using namespace std;
typedef struct TrieNode ///Trie節點宣告
{
int num; ///資料域,可根據需要進行改變
struct TrieNode *next[MAX]; ///兒子分支
} Trie;
int ans = -1;
char b[15];
void insert1(Trie *root, char *s)
{
if(root == NULL || *s == '\0' )
return ;
Trie *p = root;
while(*s != 0)
{
if(p->next[*s - 'a'] == NULL)
{
///如果當前節點還不存在,就建立新的節點
Trie *temp = (Trie *)malloc(sizeof(Trie));
for(int i = 0; i < MAX; i++)
temp->next[i] = NULL;
temp->num = 0 ;
p->next[*s - 'a'] = temp;
p = p->next[*s - 'a'];
}
else
p = p->next[*s - 'a'];
s++;
}
p->num++;
}
bool Find(Trie *rt, char *s)
{
int len = strlen(s);
for(int i = 0; i < len; i++)
{
int c = s[i] - 'a' ;
if(!rt->next[c])
return false;
rt = rt->next[c];
}
if(rt->num)
return true;
return false;
}
int main()
{
int n;
char a[15];
Trie *root = (Trie *)malloc(sizeof(Trie));
for(int i = 0; i < MAX; i++)
root->next[i] = NULL;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%s", a);
insert1(root, a);
}
while(~scanf("%s", a))
{
if(Find(root, a))
puts("exist");
else
puts("none");
}
return 0;
}
#include<bits/stdc++.h>
#define MAX 26
using namespace std;
typedef struct TrieNode ///Trie節點宣告
{
int num; ///資料域,可根據需要進行改變
struct TrieNode *next[MAX]; ///兒子分支
} Trie;
int ans = -1;
char b[15];
void insert1(Trie *root, char *s)
{
if(root == NULL || *s == '\0'
return ;
Trie *p = root;
while(*s != 0)
{
if(p->next[*s - 'a'] == NULL)
{
///如果當前節點還不存在,就建立新的節點
Trie *temp = (Trie *)malloc(sizeof(Trie));
for(int i = 0; i < MAX; i++)
temp->next[i] = NULL;
temp->num = 0
p->next[*s - 'a'] = temp;
p = p->next[*s - 'a'];
}
else
p = p->next[*s - 'a'];
s++;
}
p->num++;
}
bool Find(Trie *rt, char *s)
{
int len = strlen(s);
for(int i = 0; i < len; i++)
{
int c = s[i] - 'a'
if(!rt->next[c])
return false;
rt = rt->next[c];
}
if(rt->num)
return true;
return false;
}
int main()
{
int n;
char a[15];
Trie *root = (Trie *)malloc(sizeof(Trie));
for(int i = 0; i < MAX; i++)
root->next[i] = NULL;
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%s", a);
insert1(root, a);
}
while(~scanf("%s", a))
{
if(Find(root, a))
puts("exist");
else
puts("none");
}
return 0;
}