Find all strings that match specific pattern in a dictionary in C++

C++Server Side ProgrammingProgramming

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
raja
Published on 01-Nov-2019 06:28:22
Advertisements