当前位置:网站首页>890. Find and Replace Pattern

890. Find and Replace Pattern

2022-06-13 05:17:00 SUNNY_CHANGQI

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

在这里插入图片描述

原网站

版权声明
本文为[SUNNY_CHANGQI]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_38396940/article/details/125249668