资讯详情

890. Find and Replace Pattern

The description of the problem

Given a list of strings words and a string pattern, return a list of words[i] that match pattern. You may return the answer in any order.  A word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the desired word.  Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.  来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/find-and-replace-pattern 

an example

Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" Output: ["mee","aqq"] Explanation: "mee" matches the pattern because there is a permutation { 
        a -> m, b -> e, ...}.  "ccc" does not match the pattern because { 
        a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.  来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/find-and-replace-pattern 

The codes for above problem

#include <vector> #include <iostream> #include <algorithm> using namespace std;
class Solution { 
        
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) { 
        
        vector<string> res;
        for (auto &word : words) { 
        
            if (isMatch(word, pattern)) { 
        
                res.push_back(word);
            }
        }
        return res;
    }
    bool isMatch(string& word, string& pattern){ 
        
        if (word.size() != pattern.size()) return false;
        vector<int> map(26, -1);
        for (int i = 0; i < word.size(); i++) { 
        
            if (map[word[i] - 'a'] == -1) { 
        
                // check the pattern[i] - 'a' is in the map or not
                if (find(map.begin(), map.end(), pattern[i] - 'a') != map.end()) { 
        
                    return false;
                }
                map[word[i] - 'a'] = pattern[i] - 'a';
            } else if (map[word[i] - 'a'] != pattern[i] - 'a') { 
        
                return false;
            }
        }
        return true;
    }
};
int main()
{ 
        
    Solution s;
    vector<string> words = { 
        "abc","deq","mee","aqq","dkd","ccc"};
    string pattern = "abb";
    vector<string> res = s.findAndReplacePattern(words, pattern);
    std::cout << "res: ";
    for (auto &word : res) { 
        
        std::cout << word << " ";
    }
    std::cout << std::endl;
    return 0;
}

The corresponding results

$ ./test
res: mee aqq

在这里插入图片描述

标签: 二极管模块mee75

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台