Print all valid words that are possible using Characters of Array in C++


Ib this problem, we are given a set of words and an array of character and we have to check if the words are possible using the characters of the array.

Let’s take an example to understand the problem better −

Input : words[] : {‘go’ , ‘hi’ , ‘run’ , ‘on’ , ‘hog’ , ‘gone’}
   Char[] : {‘a’ , ‘o’ , ‘h’ , ‘g’}
Output : go , hog.

Explanation − Out of the words, the words that contain the given characters are - go, hog and rest don’t include characters in the char array.

To solve this problem, we will use the trie data structure. In this trie, we will store all the words and then search the words in trie based on the letters of the array.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
#define char_int(c) ((int)c - (int)'a')
#define int_to_char(c) ((char)c + (char)'a')
struct TrieNode{
   TrieNode *Child[26];
   bool leaf;
};
TrieNode *getNode(){
   TrieNode * newNode = new TrieNode;
   newNode->leaf = false;
   for (int i =0 ; i< 26 ; i++)
      newNode->Child[i] = NULL;
   return newNode;
}
void insertnode(TrieNode *root, char *Key){
   int n = strlen(Key);
   TrieNode * pChild = root;
   for (int i=0; i<n; i++){
      int index = char_int(Key[i]);
      if (pChild->Child[index] == NULL)
         pChild->Child[index] = getNode();
      pChild = pChild->Child[index];
   }
   pChild->leaf = true;
}
void vaidword(TrieNode *root, bool Hash[], string str){
   if (root->leaf == true)
      cout << str << "\t" ;
   for (int K =0; K < 26; K++){
      if (Hash[K] == true && root->Child[K] != NULL ){
         char c = int_to_char(K);
         vaidword(root->Child[K], Hash, str + c);
      }
   }
}
void PrintAllWords(char Arr[], TrieNode *root, int n){
   bool Hash[26];
   for (int i = 0 ; i < n; i++)
   Hash[char_int(Arr[i])] = true;
   TrieNode *pChild = root ;
   string str = "";
   for (int i = 0 ; i < 26 ; i++){
      if (Hash[i] == true && pChild->Child[i] ){
         str = str+(char)int_to_char(i);
         vaidword(pChild->Child[i], Hash, str);
         str = "";
      }
   }
}
int main(){
   char Dict[][20] = {"go" , "hi" , "run" , "on" , "hog" , "gone"} ;
   TrieNode *root = getNode();
   int n = sizeof(Dict)/sizeof(Dict[0]);
   for (int i=0; i<n; i++)
      insertnode(root, Dict[i]);
   char arr[] = {'a', 'o', 'g', 'h'} ;
   int N = sizeof(arr)/sizeof(arr[0]);
   cout<<"The words which are valid\t";
   PrintAllWords(arr, root, N);
   return 0;
}

Output

The words which are valid go hog

Updated on: 03-Jan-2020

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements