zoukankan      html  css  js  c++  java
  • 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:

    class Solution {
    public:
        vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
            vector<string> res;
            for (const auto& word : words) {
                if (match(word, pattern)) {
                    res.push_back(word);
                }
            }
    
            return res;
        }
        
    private:
        bool match(const string& word, const string& pattern) {
            if (word.size() != pattern.size()) {
                return false;
            }
            //建立双映射
            unordered_map<char, char> word2Pattern;
            unordered_map<char, char> pattern2Word;
            int N = word.size();
            for (int i = 0; i < N; i++) {
                auto wordChar = word[i];
                auto patternChar = pattern[i];
                if (!word2Pattern.count(wordChar) && !pattern2Word.count(patternChar)) {
                    word2Pattern[wordChar] = patternChar;
                    pattern2Word[patternChar] = wordChar;
                } else {
                    if (word2Pattern[wordChar] != patternChar || pattern2Word[patternChar] != wordChar) {
                        return false;
                    }
                }
            }
    
            return true;
        }
    }; 

    题解2:

    class Solution {
    public:
        vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
            vector<string> res;
            for(int i=0;i<words.size();i++){
                if(check(words[i],pattern)) res.push_back(words[i]);
            }
            return res;
        }
        bool check(string word,string pattern){
            if(word.length()!=pattern.length()) return false;
            for(int i=0;i<pattern.length();i++){
                if(word.find(word[i])!=pattern.find(pattern[i])) return false;
            }
        return true;
        }
    };
  • 相关阅读:
    js通过class获取元素时的兼容性解决方案
    html5的八大特性
    typeof与instanceof的区别
    evel()与JSON.parset()的区别
    apt-get出现的问题
    Linux下开启计划任务日志
    ls
    win10自带IE上不了网的解决办法
    crontab -e文件存放路径
    Linux系统下面crontab选择默认编译器
  • 原文地址:https://www.cnblogs.com/USTC-ZCC/p/14606907.html
Copyright © 2011-2022 走看看