使用C ++中的数组字符打印所有可能的有效单词

关于这个问题,我们给了一组单词和一个字符数组,我们必须使用数组的字符检查单词是否可能。

让我们举个例子来更好地理解问题-

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

解释-在单词中,包含给定字符的单词为-go,hog和rest在char数组中不包含字符。

为了解决这个问题,我们将使用trie数据结构。在这个特里,我们将存储所有单词,然后根据数组的字母在特里中搜索单词。

示例

#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;
}

输出结果

The words which are valid go hog