|
| 1 | +/* |
| 2 | +Problem Statement |
| 3 | +
|
| 4 | +Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order. |
| 5 | +
|
| 6 | +A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word. |
| 7 | +
|
| 8 | +Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter. |
| 9 | +
|
| 10 | +Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" |
| 11 | +Output: ["mee","aqq"] |
| 12 | +Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. |
| 13 | +"ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter. |
| 14 | +
|
| 15 | +Constraints: |
| 16 | +1 <= pattern.length <= 20 |
| 17 | +1 <= words.length <= 50 |
| 18 | +words[i].length == pattern.length |
| 19 | +pattern and words[i] are lowercase English letters. |
| 20 | +
|
| 21 | +*/ |
| 22 | + |
| 23 | +/* |
| 24 | +Time Complexity: O(N∗K), where N is the number of words, and K is the length of each word. |
| 25 | +Space Complexity: O(N∗K), the space used by the answer. |
| 26 | +*/ |
| 27 | + |
| 28 | +#include<bits/stdc++.h> |
| 29 | +using namespace std; |
| 30 | + |
| 31 | +vector<string> findAndReplacePattern(vector<string> &words, string pattern) |
| 32 | +{ |
| 33 | + vector<string> ans; |
| 34 | + for (int i = 0; i < words.size(); i++) |
| 35 | + { |
| 36 | + bool flag = true; |
| 37 | + unordered_map<char, char> wordToPattern; |
| 38 | + unordered_map<char, char> patternToWord; |
| 39 | + for (int j = 0; j < pattern.length(); j++) |
| 40 | + { |
| 41 | + char wc = words[i][j]; |
| 42 | + char pc = pattern[j]; |
| 43 | + if (wordToPattern.count(wc) < 1) |
| 44 | + wordToPattern[wc] = pc; |
| 45 | + if (patternToWord.count(pc) < 1) |
| 46 | + patternToWord[pc] = wc; |
| 47 | + |
| 48 | + if (patternToWord[pc] != wc || wordToPattern[wc] != pc) |
| 49 | + { |
| 50 | + flag = false; |
| 51 | + break; |
| 52 | + } |
| 53 | + } |
| 54 | + if (flag == true) |
| 55 | + ans.push_back(words[i]); |
| 56 | + } |
| 57 | + return ans; |
| 58 | +} |
| 59 | + |
| 60 | +int main() |
| 61 | +{ |
| 62 | + vector<string> words={"abc","deq","mee","aqq","dkd","ccc"}; |
| 63 | + string pattern="abb"; |
| 64 | + vector<string> ans=findAndReplacePattern(words,pattern); |
| 65 | + for(string str:ans) |
| 66 | + cout<<str<<" "; |
| 67 | + return 0; |
| 68 | +} |
| 69 | + |
0 commit comments