TheAlgorithms-C-Plus-Plus/data_structure/TrieTree.cpp

97 lines
2.1 KiB
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream>
#include <string.h>
#include <stdbool.h>
2018-10-11 12:20:16 +08:00
using namespace std;
2018-10-11 12:27:49 +08:00
// structure definition
2018-10-11 12:20:16 +08:00
typedef struct trie
{
struct trie *arr[26];
bool isEndofWord;
} trie;
2019-08-21 10:10:08 +08:00
// create a new node for trie
2018-10-11 12:20:16 +08:00
trie *createNode()
{
trie *nn = new trie();
for (int i = 0; i < 26; i++)
nn->arr[i] = NULL;
nn->isEndofWord = false;
return nn;
}
2019-08-21 10:10:08 +08:00
// insert string into the trie
void insert(trie *root, char *str)
2018-10-11 12:20:16 +08:00
{
for (int i = 0; i < strlen(str); i++)
{
int j = str[i] - 'a';
if (root->arr[j])
{
root = root->arr[j];
}
else
{
root->arr[j] = createNode();
root = root->arr[j];
}
}
root->isEndofWord = true;
}
2018-10-11 12:27:49 +08:00
// search a string exists inside the trie
2019-08-21 10:10:08 +08:00
bool search(trie *root, char *str, int index)
2018-10-11 12:20:16 +08:00
{
if (index == strlen(str))
{
if (!root->isEndofWord)
return false;
return true;
}
int j = str[index] - 'a';
if (!root->arr[j])
return false;
return search(root->arr[j], str, index + 1);
}
2018-10-11 12:27:49 +08:00
/* removes the string if it is not a prefix of any other
string, if it is then just sets the endofword to false, else
removes the given string*/
2019-08-21 10:10:08 +08:00
bool deleteString(trie *root, char *str, int index)
2018-10-11 12:20:16 +08:00
{
if (index == strlen(str))
{
if (!root->isEndofWord)
return false;
root->isEndofWord = false;
for (int i = 0; i < 26; i++)
return false;
return true;
}
int j = str[index] - 'a';
if (!root->arr[j])
return false;
2019-08-21 10:10:08 +08:00
bool var = deleteString(root, str, index + 1);
2018-10-11 12:20:16 +08:00
if (var)
{
root->arr[j] = NULL;
if (root->isEndofWord)
return false;
else
{
int i;
for (i = 0; i < 26; i++)
if (root->arr[i])
return false;
return true;
}
}
}
int main()
{
trie *root = createNode();
insert(root, "hello");
insert(root, "world");
int a = search(root, "hello", 0);
int b = search(root, "word", 0);
printf("%d %d ", a, b);
return 0;
}