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
Updated on: 2019-11-01T06:28:22+05:30

643 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements