890. Find and Replace Pattern

方法一:两个map
分别记录下每对char的对应关系。
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
vector<string> res;
for (auto& str : words) {
if (match(str, pattern))
res.push_back(str);
}
return res;
}
private:
unordered_map<char, char> m, reverseMap;
bool match(string& str, string& pattern) {
if (str.size() != pattern.size())
return false;
m.clear();
reverseMap.clear();
for (int i = 0; i < str.size(); ++i) {
if (m.find(str[i]) != m.end())
if (m[str[i]] != pattern[i])
return false;
if (reverseMap.find(pattern[i]) != reverseMap.end())
if (reverseMap[pattern[i]] != str[i])
return false;
m[str[i]] = pattern[i];
reverseMap[pattern[i]] = str[i];
}
return true;
}
};
方法二:
标准化。
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
string patStr = getStr(pattern);
vector<string> res;
for (auto word : words)
if (patStr == getStr(word)) {
res.push_back(word);
}
return res;
}
private:
string getStr(string word) {
unordered_map<char, int> m;
for (char c : word)
if (m.find(c) == m.end())
m[c] = m.size();
for (int i = 0; i < word.size(); ++i)
word[i] = 'a' + m[word[i]];
return word;
}
};//这个思路确实有点意思。
//标准化,将字符全用a,b,c...表示。比如mee->abb,dkd->aba,这样匹配的字符串它们的标准化字符串是一样的。
浙公网安备 33010602011771号