1,题目要求
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.
对单词中的字母按照pattern进行映射,判断是否满足pattern的模式。
2,题目思路
对于这道题,并不是一个简单的模式匹配,而是一个映射的匹配。具体差别就在于,映射的关键在于对应,而不在于具体字母。对于“mee”,我们就可以将其认定为“abb”的方式去映射,也就是“122”的方式。
因此,在具体实现上,就要去寻找这样的map。
3,程序源码
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
string p = normHelper(pattern);
vector<string> res;
for(auto w : words) if(normHelper(w) == p) res.push_back(w);
return res;
}
private:
string normHelper(string s)
{
unordered_map<char, int> m;
for(auto c : s)
if(m.count(c) == 0)
m[c] = m.size();
for(int i = 0;i<s.size();i++)
s[i] = 'a' + m[s[i]];
return s;
}
};