[leetcode]890. 查找和替换模式

题目


你有一个单词列表 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. 1 <= words.length <= 50
  2. 1 <= pattern.length = words[i].length <= 20

 思路


这道题与LeetCode.205.Isomorphic Strings 基本一样,只不过LeetCode205只是判断两个字符串是否是同构,而这道题是从多个字符串中选出与目标字符串同构的字符串.

LeetCode.205.Isomorphic Strings传送门:https://blog.csdn.net/Strengthennn/article/details/81840471

代码

class Solution {
public:
    bool isPattern(string s, string t){
        int m = s.size();
        int n = t.size();
        
        if(m != n)
            return false;
        
        map<char, char> mp1;
        map<char, char> mp2;
        
        for(int i=0; i<m; i++){
            map<char, char>::iterator it;
            
            if(mp1.find(s[i]) != mp1.end()){
                if(mp1[s[i]] != t[i]){
                    return false;
                }    
            }else{
                mp1[s[i]] = t[i];
            }
        }

        for(int i=0; i<n; i++){
            map<char, char>::iterator it;
            
            if(mp2.find(t[i]) != mp2.end()){
                if(mp2[t[i]] != s[i]){
                    return false;
            }    
            }else{
               mp2[t[i]] = s[i];
            }
        }
        
        return true;
   
    }

    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> ans;
        int n = words.size();
        
        for(int i=0; i<n; i++){
            if(isPattern(words[i], pattern)){
                ans.push_back(words[i]);
            }else{
                ;
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/Strengthennn/article/details/81840846