题目:
You have a list of words
and a pattern
, and you want to know which words in words
matches the pattern.
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.
(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.)
Return a list of the words in words
that match the given pattern.
You may return the answer in any order.
Example 1:
Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
Note:
1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20
题目大意是将一个vector<string>对象里的每一个string与给定的string比较,判断是否是同一模式。实际上就是比较两个字符串,两个字符串中相同索引的字符存在映射关系,并且映射关系是双射。
比较的方法是同时遍历两个字符串str与pattern,定义一个map<char,char> ms;
若pattern[i]在ms中即表示已经存在映射关系,再判断str[i]是否等于ms[pattern[i]],若是不等于则表示不满足双射(不匹配)(此时出现同一元素被映射到不同的元素上),否则继续比较;
若pattern[i]不在ms中即表示pattern[i]还不存在映射关系,再继续判断str[i]是否已经被映射了,若是被映射了则表示不满足双射(不匹配)(此时不同的元素映射到同一个元素上),否则继续比较。
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for(auto val : words){
if(detectFun(val, pattern, val.size()))
res.push_back(val);
}
return res;
}
bool detectFun(string& str, string& pattern, int len){
map<char, char> ms;
set<char> sc;
for(int i = 0; i < len; i++){
if(ms.find(pattern[i]) == ms.end()){
if(sc.find(str[i]) != sc.end())
return false;
ms[pattern[i]] = str[i];
sc.insert(str[i]);
}else{
if(ms[pattern[i]] != str[i])
return false;
}
}
return true;
}
};