Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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#include #include using namespace std; string stringEncode(string str) { unordered_map 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 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 dict = {"abb", "xyz", "aab", "kmm"}; string pattern = "stt"; matchedPattern(dict, pattern); }
Output
kmm abb
Advertisements
