分析
我们只用模拟匹配替换过程即可,需要注意的是我们在匹配过程中需要使用两个map
,来保证A -> B
和B ->A
的一致性。
代码
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> result;
for(auto word : words){
int i;
unordered_map<char, char> p2wmaps, w2pmaps;
if(word.size() != pattern.size())
continue;
for(i = 0; i < pattern.size(); i++){
if(p2wmaps.count(pattern[i])){
if(p2wmaps[pattern[i]] != word[i])
break;
}
else{
if(w2pmaps.count(word[i]))
break;
p2wmaps[pattern[i]] = word[i];
w2pmaps[word[i]] = pattern[i];
}
}
if(i == pattern.size())
result.push_back(word);
}
return result;
}
};