Trie

Jimmy (xiaoke) Shen
1 min readJul 20, 2021

Distinct Substrings

A naive trie solution

struct Trie{
char c;
vector<Trie*> children;
Trie(char c): c(c) {
children.assign(26, nullptr);
}
};
int solve(string s) {
if (s.empty())return 0;
const int n = s.length();
Trie* root = new Trie('#');
Trie* curr = root;
int ret = 0;
for (int i = 0; i < n; ++i){
curr = root;
for (int j = i; j < n; ++j){
Trie* child = curr -> children[s[j] - 'a'];
if (child == nullptr){
ret++;
Trie* newTrie = new Trie(s[j]);
curr -> children[s[j] - 'a'] = newTrie;
}
curr = curr -> children[s[j] - 'a'];
}
}
return ret;
}

For this specified problem, we don’t need to record the character for each Trie node as the children’s index can already tell us the character information.

struct Trie{
vector<Trie*> children;
Trie(){
children.assign(26, nullptr);
}
};
int solve(string s) {
if (s.empty())return 0;
const int n = s.length();
Trie* root = new Trie();
Trie* curr = root;
int ret = 0;
for (int i = 0; i < n; ++i){
curr = root;
for (int j = i; j < n; ++j){
Trie* child = curr -> children[s[j] - 'a'];
if (child == nullptr){
ret++;
Trie* newTrie = new Trie();
curr -> children[s[j] - 'a'] = newTrie;
}
curr = curr -> children[s[j] - 'a'];
}
}
return ret;
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet