在 C++ 中使用数组字符打印所有可能的有效单词
在此问题中,我们提供了一组单词和一个字符数组,并且我们必须检查这些单词是否可以使用数组中的字符。
我们举一个例子来更好地理解这个问题 −
Input : words[] : {‘go’ , ‘hi’ , ‘run’ , ‘on’ , ‘hog’ , ‘gone’}
Char[] : {‘a’ , ‘o’ , ‘h’ , ‘g’}
Output : go , hog.说明 − 在这些单词中,包含给定字符的单词是 - go、hog 和 rest 不包含 char 数组中的字符。
为了解决这个问题,我们将使用 Trie 数据结构。在这个 Trie 结构中,我们将存储所有单词,然后根据数组的字母在 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
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP