leetcode 890. 查找和替换模式 c++

中等

202

相关企业

你有一个单词列表 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 映射到同一个字母。

扫描二维码关注公众号,回复: 16643946 查看本文章

提示:

  • 1 <= words.length <= 50
  • 1 <= pattern.length = words[i].length <= 20

通过次数

30.5K

提交次数

38.7K

通过率

78.8%

题解思路:要去是映射关系,首先想到了unordered_set,但是将谁作为主键是一个问题,分别试过两次,都不行。问题在于要实现一个一对一的映射,而且键和值都不能重复,于是灵光一闪,那我就两个unordered_set不就行了?于是就有了下面的代码:

class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string>res;
        for(auto i:words)
        {
            bool flag=true;
            unordered_map<char,char> Hashmap;
            unordered_map<char,char> Hashmap2;
            unordered_map<char,char>::iterator it;
            for(int j=0;j<pattern.size();j++)
            {
                it = Hashmap.find(i[j]);
                if(it!=Hashmap.end())
                {
                    if(it->second !=pattern[j])
                    {
                        flag=false;
                        break;
                    }
                }
                else
                {
                    Hashmap[i[j]]=pattern[j];
                }

                it = Hashmap2.find(pattern[j]);
                if(it!=Hashmap2.end())
                {
                    if(it->second !=i[j])
                    {
                        flag=false;
                        break;
                    }
                }
                else
                {
                    Hashmap2[pattern[j]]=i[j];
                }
            }
            if(flag)
            {
                res.push_back(i);
            }
        }
        return res;
    }
};

顺利通过了。

猜你喜欢

转载自blog.csdn.net/weixin_41579872/article/details/127819467