- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find all strings that match specific pattern in a dictionary in C++
Consider we have a list of strings called dictionary. We have another pattern string. Our task is to find those strings that matches the pattern. Suppose the dictionary is like [“abb”, “xyz”, “aab”, “kmm”], and pattern is “stt”, then the results will be “abb”, and “kmm”. As the pattern has one letter at first, then the two same letters, so it will follow same pattern strings.
To solve this problem, we will encode the pattern in such a way that any word from the dictionary, that matches the pattern, will have the same hash like the pattern after encoding. We will iterate through all words in dictionary and display them where the hash is same.
Example
#include<iostream> #include<unordered_map> #include<unordered_set> using namespace std; string stringEncode(string str) { unordered_map<char, int> map; string encoded_str = ""; int i = 0; for (char ch : str) { if (map.find(ch) == map.end()) map[ch] = i++; encoded_str += to_string(map[ch]); } return encoded_str; } void matchedPattern(unordered_set<string> dict, string pattern) { int patt_len = pattern.length(); string hash = stringEncode(pattern); for (string word : dict) { if (word.length() == patt_len && stringEncode(word) == hash) cout << word << " "; } } int main() { unordered_set<string> dict = {"abb", "xyz", "aab", "kmm"}; string pattern = "stt"; matchedPattern(dict, pattern); }
Output
kmm abb
- Related Articles
- How do find out all elements that match a specific condition in JavaScript?
- Print all words matching a pattern in CamelCase Notation Dictionary in C++
- Count strings that end with the given pattern in C++
- Find All Good Strings in C++
- All combinations of strings that can be used to dial a number in C/C++?
- How to find all tables that contains two specific columns in MySQL?
- How to match strings that aren't entirely digits in JavaScript?
- Use Pattern class to match in Java
- Python - Find all the strings that are substrings to the given list of strings
- Remove all elements of a List that match the conditions defined by the predicate in C#
- Check whether the Dictionary contains a specific value or not in C#
- Zig-Zag pattern in strings in JavaScript?
- C# Program to match all the digits in a string
- Match specific word in regex in JavaScript?
- Find a specific column in all the tables in a database?

Advertisements