用 C++ 列印與駝峰法表示法字典中模式匹配的所有單詞


在這個問題中,我們得到一個駝峰法的字串陣列和一個模式。我們必須列印陣列中與給定模式匹配的所有字串。

字串陣列 是一個元素為字串資料型別的陣列。

駝峰法 是程式設計中常見的命名方法,按照這種方法,新單詞的第一個字母大寫,其餘全部小寫。

示例 − iLoveProgramming

問題 − 找出與給定模式匹配的所有字串。

示例

Input : “TutorialsPoint” , “ProgrammersPoint” , “ProgrammingLover” , “Tutorials”.
Pattern : ‘P’
Output : “TutorialsPoint” ,
“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" , "TutorialsPoint" , "LearnersPoint", "TutorialsPointsPrograming" , "programmingTutorial"};
   string pattern = "TP";
   findAllMatch(dictionary, pattern);
   return 0;
}

輸出

TP
TutorialsPoint
TutorialsPointsPrograming

更新於: 2020-01-03

261 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告