Advertisement
Fastrail08

Word Pattern Matching

May 10th, 2025 (edited)
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void wordPattern(string s, int index, string &str1, string &str2, unordered_set<char> &uniqueSet, unordered_map<char, string> &mapping){
  5.     if(index >= str2.size()){
  6.         string stringFormed = "";
  7.         for(char c : str2){
  8.             stringFormed += mapping[c];
  9.         }
  10.         if(stringFormed == str1){
  11.             for(char c : str2){
  12.                 cout << c << ": " << mapping[c] << " ";
  13.             }
  14.             cout << '\n';
  15.         }
  16.         return;
  17.     }
  18.     if(s == ""){
  19.         return;
  20.     }
  21.     if(uniqueSet.count(str2[index]) == 0){
  22.         for(int i = 1; i < s.size(); i++){
  23.             string substring = s.substr(0, i);
  24.             string ros = s.substr(i);
  25.             mapping[str2[index]] = substring;
  26.             uniqueSet.insert(str2[index]);
  27.             wordPattern(ros, index + 1, str1, str2, uniqueSet, mapping);
  28.             uniqueSet.erase(str2[index]);
  29.         }
  30.         mapping.erase(str2[index]);
  31.     }
  32.     else{
  33.         wordPattern(s, index + 1, str1, str2, uniqueSet, mapping);
  34.     }
  35. }
  36.  
  37. int main() {
  38.     // your code goes here
  39.     string str1, str2;
  40.     cin >> str1 >> str2;
  41.     unordered_set<char> uniqueSet;
  42.     unordered_map<char, string> mapping;
  43.     wordPattern(str1, 0, str1, str2, uniqueSet, mapping);
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement