From f55423a57977c3ba39bcedcad6b1fd93dc1b1ee3 Mon Sep 17 00:00:00 2001 From: paraggoyal28 <2015uec1209@mnit.ac.in> Date: Sun, 18 Oct 2020 18:08:11 +0530 Subject: [PATCH] trie code added and tested --- Tries/README.md | 25 ++++++++++++++++++++++ Tries/tries.cpp | 56 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 Tries/README.md create mode 100644 Tries/tries.cpp diff --git a/Tries/README.md b/Tries/README.md new file mode 100644 index 0000000..2354e86 --- /dev/null +++ b/Tries/README.md @@ -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) diff --git a/Tries/tries.cpp b/Tries/tries.cpp new file mode 100644 index 0000000..8387e79 --- /dev/null +++ b/Tries/tries.cpp @@ -0,0 +1,56 @@ +#include +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; +} \ No newline at end of file