1. 程式人生 > >[leetcode]890. 查詢和替換模式

[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只是判斷兩個字串是否是同構,而這道題是從多個字串中選出與目標字元串同構的字串.

程式碼

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;
    }
};