在C ++中的CamelCase符号词典中打印与模式匹配的所有单词

在这个问题中,我们得到了一个驼峰式的字符串数组和一个模式。我们必须打印与给定模式匹配的所有数组字符串。

字符串数组是其中元素为字符串数据类型的数组。

camelCase是编程中常用的命名方法,通过这种方式,新单词的第一个字母以大写字母开头,其余全部为小写字母。

示例-iLoveProgramming

问题-查找与给定模式匹配的所有字符串。

示例-

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

说明-我们已经考虑了所有其中带有“ P”的字符串。

为了解决这个问题,我们将字典的所有键添加到树上,然后使用大写字符。并处理树中的单词并打印所有与模式匹配的单词。

示例

#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" , "nhooo" , "LearnersPoint", "nhooosPrograming" , "programmingTutorial"};
   string pattern = "TP";
   findAllMatch(dictionary, pattern);
   return 0;
}

输出结果

TP
nhooo
nhooosPrograming