Find and Replace Pattern
给一个string数组和一个pattern string, 求满足这个pattern的string.
因为是pattern, 所以用两个map互相把里面的char建立mapping即可.
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for(auto w : words){
if(w.size() != pattern.size()) // must be same length
continue;
unordered_map<char, char> map;
unordered_map<char, char> rmap;
bool add = true;
for(int i = 0; i < w.size(); i++){
if(map.find(pattern[i]) != map.end() || rmap.find(w[i]) != map.end()){
if(map[pattern[i]] != w[i] || rmap[w[i]] != pattern[i]){
add = false;
break;
}
}else{
map[pattern[i]] = w[i];
rmap[w[i]] = pattern[i];
}
}
if(add)
res.push_back(w);
}
return res;
}
};