Problem
You have a list of words
and a pattern
, and you want to know which words in words
matches the pattern.
Example
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.
Answer
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
string nP = normalize(pattern);
for (auto& word: words) {
if (normalize(word) == nP) res.push_back(word);
}
return res;
}
string normalize(string& s) {
unordered_map<char,int> map;
for (auto& c : s) if (!map.count(c)) map[c] = map.size();
string nS;
for (auto& c : s) nS += map[c];
return nS;
}
};
Explanation
比较两个字符串是否具有相同的pattern
.
- 我们可以对两个字符串分别进行
normalize
normalize
的根据就是遍历每个字符,通过unordered_map
来记录该字符是字符串中出现的顺序位置.
根据字符串的出现顺序,我们可以把原字符串转化为normalize
后的字符串. - 比较两个字符串的
normalize
后是否相同就可以判断是否有相同的patter