在 C++ 中找到字典中与特定模式匹配的所有字符串


假设我们有一串被称为词典的字符串。我们有另一个模式字符串。我们的任务是找到那些与该模式匹配的字符串。假设词典为 [“abb”, “xyz”, “aab”, “kmm”],模式为 “stt”,那么结果将为 “abb” 和 “kmm”。由于该模式第一个是某一个字母,然后是两个相同的字母,因此它将遵循相同的字符串模式。

为了解决这个问题,我们将对该模式进行编码,使得任何与模式相匹配的词典中的单词,在编码后都将具有与模式相同的哈希值。我们将遍历词典中的所有单词,并显示它们的哈希值相同。

示例

#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);
}

输出

kmm abb

更新于: 01-11-2019

509 次浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.