Print all words matching a pattern in CamelCase Notation Dictionary in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of string in camelcase and a pattern. We have to print all those string of the array that match the given pattern.

The array of string is an array in which elements are of the string data type.

camelCase is a common method for naming in programming, in this way the first letter of the new word starts with an uppercase, rest all are lower case.

Example − iLoveProgramming

Problem − find all strings that match a given pattern.

Example

Input : “TutorialsPoint” , “ProgrammersPoint” , “ProgrammingLover” , “Tutorials”.
Pattern : ‘P’
Output : “TutorialsPoint” ,
“ProgrammersPoint” , “ProgrammingLover”

Explanation − We have considered all those strings that have ‘P’ in them.

To solve this problem, we will add all the keys of a dictionary to a tree and then use the uppercase characters. And process the words in the tree and print all that match the pattern.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct TreeNode{
   TreeNode* children[26];
   bool isLeaf;
   list<string> word;
};
TreeNode* getNewTreeNode(void){
   TreeNode* pNode = new TreeNode;
   if (pNode){
      pNode->isLeaf = false;
      for (int i = 0; i < 26; i++)
         pNode->children[i] = NULL;
   }
   return pNode;
}
void insert(TreeNode* root, string word){
   int index;
   TreeNode* pCrawl = root;
   for (int level = 0; level < word.length(); level++){
      if (islower(word[level]))
         continue;
      index = int(word[level]) - 'A';
      if (!pCrawl->children[index])
      pCrawl->children[index] = getNewTreeNode();
      pCrawl = pCrawl->children[index];
   }
   pCrawl->isLeaf = true;
   (pCrawl->word).push_back(word);
}
void printAllWords(TreeNode* root){
   if (root->isLeaf){
      for(string str : root->word)
         cout << str << endl;
   }
   for (int i = 0; i < 26; i++){
      TreeNode* child = root->children[i];
      if (child)
         printAllWords(child);
   }
}
bool search(TreeNode* root, string pattern){
   int index;
   TreeNode* pCrawl = root;
   for (int level = 0; level <pattern.length(); level++) {
      index = int(pattern[level]) - 'A';
      if (!pCrawl->children[index])
         return false;
      pCrawl = pCrawl->children[index];
   }
   printAllWords(pCrawl);
   return true;
}
void findAllMatch(vector<string> dictionary, string pattern){
   TreeNode* root = getNewTreeNode();
   for (string word : dictionary)
      insert(root, word);
   if (!search(root, pattern))
      cout << "No match found";
}
int main(){
   vector<string> dictionary = { "Tutorial" , "TP" , "TutorialsPoint" , "LearnersPoint", "TutorialsPointsPrograming" , "programmingTutorial"};
   string pattern = "TP";
   findAllMatch(dictionary, pattern);
   return 0;
}

Output

TP
TutorialsPoint
TutorialsPointsPrograming
raja
Published on 03-Jan-2020 10:06:35
Advertisements