用 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
广告
数据结构
网络化
RDBMS
操作系统
Java
iOS
HTML
CSS
安卓
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP