Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

trie code added and tested #186

Merged
merged 1 commit into from
Oct 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Tries/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Given a set of strings, and a target string, find whether that string exists in the set of strings. We need to implement a trie data structure to parallely search for that specific string in the set of strings.

Input Format: First line contains the number of strings in the set.
Strings are given in lower case only.
Input 1:
5
hackoctoberfest
congratulations
pagination
fragmentation
algorithms
fragment

Output: NO

Input 2:
2
yatch
boat
boat

Output: YES

Contributor
[Parag Kumar Goyal](https://github.com/paraggoyal28)
56 changes: 56 additions & 0 deletions Tries/tries.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include<bits/stdc++.h>
using namespace std;
#define ll long long

class Trie{
public:
bool isEnd;
Trie* children[26];

Trie(){
isEnd = false;
for(int i = 0; i < 25; ++i){
children[i] = NULL;
}
}

void insert(string word){
Trie* root = this;
for(int i = 0, len = word.length() ; i < len; ++i){
if(root->children[word[i]-'a']==NULL){
root->children[word[i]-'a'] = new Trie();
}
root = root->children[word[i]-'a'];
}
root->isEnd = true;
}

bool search(string word){
Trie* root = this;
for(int i = 0, len = word.length(); i < len; ++i){
if(root->children[word[i]-'a']==NULL){
return false;
}
root = root->children[word[i]-'a'];
}
return root!=NULL && root->isEnd;
}
};

int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
ll numberStrings;
cin >> numberStrings;
string s;
Trie root;
for(ll i = 0; i < numberStrings; ++i){
cin >> s;
root.insert(s);
}
string toFindString;
cin >> toFindString;
cout << root.search(toFindString) << endl;
return 0;
}