Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created April 27, 2022 21:59
Show Gist options
  • Save dgodfrey206/a0aeb0459eebc1d71d4d38a3ae5698ce to your computer and use it in GitHub Desktop.
Save dgodfrey206/a0aeb0459eebc1d71d4d38a3ae5698ce to your computer and use it in GitHub Desktop.
Suffix tree insert and search
#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
using namespace std;
struct suffix_tree {
std::string suffix;
suffix_tree* child[26] = {};
int index = 0;
bool is_end = false;
};
suffix_tree* CreateNode() {
suffix_tree* newnode = new suffix_tree();
return newnode;
}
using node = suffix_tree;
string match(string a, string b) {
size_t i = 0, j = 0;
while (i < a.size() && j < b.size() && a[i] == b[j])
i++, j++;
return a.substr(0, i);
}
void Insert(node* head, string s) {
node* current = head;
for (size_t i = 0; i < s.size(); i++) {
string word = s.substr(i);
node** pChild = &current->child[word[0] - 'a'];
if (*pChild == NULL) {
*pChild = new node();
(*pChild)->suffix = word;
(*pChild)->is_end = true;
(*pChild)->index = i;
} else {
string tmp = (*pChild)->suffix;
if (word == tmp)
return;
string pre = match(word, tmp);
(*pChild)->suffix = pre;
if (i < word.size() - 1) {
Insert(*pChild, word.substr(i + 1));
(*pChild)->is_end = false;
}
if (tmp.size() > 1) {
Insert(*pChild, tmp.substr(1));
(*pChild)->is_end = false;
}
}
}
}
bool Search(node* head, string word) {
if (word.empty())
return true;
node* current = head;
for (size_t i = 0; i < word.length();) {
current = current->child[word[i] - 'a'];
if (current == NULL)
return false;
size_t j = 0;
//cout<<boolalpha<<((bool)current->child['b'-'a'])<<endl;
for (; i < word.size() && j < current->suffix.size() &&
word[i] == current->suffix[j];) {
i++, j++;
}
if (i == word.size()) {
cout << current->index << " ";
return true;
}
}
return true;
}
int main() {
auto* root = new suffix_tree;
string s = "abcbacl";
string str = "acl";
cout << s << "\n" << str << endl;
Insert(root, s);
if (Search(root, str) == true)
cout << "Found\n";
else
cout << "Not found\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment