在 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.