【leetcode刷题】T95-查找和替换模式

时间:2022-06-26
本文章向大家介绍【leetcode刷题】T95-查找和替换模式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

【题目】

你有一个单词列表 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

【思路】

使用两个字典/map,保证单词和pattern的字符一一对应。

【代码】

python版本

class Solution(object):
    def findAndReplacePattern(self, words, pattern):
        """
        :type words: List[str]
        :type pattern: str
        :rtype: List[str]
        """
        res = []
        for word in words:
            # 长度不同,肯定不满足
            if len(word) != len(pattern):
                continue
            d1 = {}
            d2 = {}
            i = 
            # 模式相同
            while i < len(pattern):
                p = pattern[i]
                if p not in d1:
                    d1[p] = word[i]
                elif d1[p] != word[i]:
                    break
                if word[i] not in d2:
                    d2[word[i]] = p
                elif d2[word[i]] != p:
                    break
                i += 
            if i == len(pattern):
                res.append(word)
        return res

C++版本

class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        map<char, char> d1;
        map<char, char> d2;
        vector<string> res;
        for(auto word: words){
            // 长度不同,不满足
            if(word.size() != pattern.size())
                continue;
            // 清空
            d1.clear();
            d2.clear();
            int i = ;
            for(i=; i<pattern.size(); i++){
                if(d1.find(word[i]) == d1.end())
                    d1[word[i]] = pattern[i];
                else
                    if(d1[word[i]] != pattern[i])
                        break;
                if(d2.find(pattern[i]) == d2.end())
                    d2[pattern[i]] = word[i];
                else
                    if(d2[pattern[i]] != word[i])
                        break;
            }
            if(i == pattern.size())
                res.push_back(word);
        }
        return res;
    }
};