题目:
你有一个单词列表 words 和一个模式 pattern,你想知道 words 中的哪些单词与模式匹配。
如果存在字母的排列 p ,使得将模式中的每个字母 x 替换为 p(x) 之后,我们就得到了所需的单词,那么单词与模式是匹配的。
(回想一下,字母的排列是从字母到字母的双射:每个字母映射到另一个字母,没有两个字母映射到同一个字母。)
返回 words 中与给定模式匹配的单词列表。
你可以按任何顺序返回答案。
示例:
输入:words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
输出:["mee","aqq"]
解释:
"mee" 与模式匹配,因为存在排列 {a -> m, b -> e, ...}。
"ccc" 与模式不匹配,因为 {a -> c, b -> c, ...} 不是排列。
因为 a 和 b 映射到同一个字母。
提示:
1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20
分析:
words数组的每个word与pattern比较,有如下情况:
- 当两者大小不一样,直接判断下一个word
- 当两者大小相同时,判断word中与pattern中的char是一对一的映射关系,因此可以利用一个map<char,char> mp 和 set< char > used两个容器,判断pattern中第i个字符s和word中第i个字符w:
1.当mp中不含s时,如果used已经有了w,说明w已经和pattern之前的某个字符建立了映射,此时一个w对应多个pattern中的字符,返回flag=false;否则,则要新建立s和w的映射,同时将w加入到used中。
2. 当mp中含有s时,要判断mp[s]是否等于w,如果不等于则说明一个s对应多个不同的w,返回flag=false。
3. 当word遍历完,此时flag为true则将word加入输出结果中。
代码:
class Solution {
public:
vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
int len = pattern.size();
vector<string> res;
map<char,char> mp;
set<char> used;
for(auto word:words){
mp.clear();
used.clear();
bool flag=true;
if(word.size()!=len)
continue;
for(int i=0; i<len; ++i){
if(mp.find(pattern[i])==mp.end()){//当pattern中的字符不在mp中
if(used.find(word[i])!=used.end()){//word中字符已经在了,说明造成了一对多的映射
flag = false; break;
}
mp[pattern[i]]=word[i];
used.insert(word[i]);
} else {//存在时,判断是否是一对一映射
if(mp[pattern[i]]!=word[i]){
flag=false; break;
}
}
}
if(flag==true)
res.push_back(word);
}
return res;
}
};
参考:
https://leetcode-cn.com/problems/find-and-replace-pattern/comments/
https://leetcode-cn.com/problems/find-and-replace-pattern/comments/86647