1. 程式人生 > >890. Find and Replace Pattern(python+cpp)

890. Find and Replace Pattern(python+cpp)

題目:

You have a list of words and a pattern, and you want to know which words in words matches the pattern.
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.)
Return a list of the words in words

that match the given pattern.
You may return the answer in any ord
Example 1:

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.  

Note:
1 <= words.length <= 50
1 <= pattern.length = words[i].length <= 20

解釋:
205. Isomorphic Strings(python+cpp)290. Word Pattern(python+cpp)寫法一樣,用兩個字典實現。205的程式碼可以直接使用,可以把word pattern的過程寫成一個函式。
python程式碼:

class Solution:
    def findAndReplacePattern(self, words, pattern):
        """
        :type words: List[str]
        :type pattern: str
        :rtype: List[str]
        """
def isIsomorphic(s, t): if len(s)!=len(t): return False s_dict={} t_dict={} for i in range(len(s)): if s[i] not in s_dict: s_dict[s[i]]=t[i] else: if s_dict[s[i]]==t[i]: continue else: return False if t[i] in t_dict: if t_dict[t[i]]!=s[i]: return False else: t_dict[t[i]]=s[i] return True result=[ word for word in words if isIsomorphic(word,pattern)] return result

c++程式碼:

class Solution {
public:
    vector<string> findAndReplacePattern(vector<string>& words, string pattern) {
        vector<string> result;
        for (auto  word:words)
        {
            if (isIsomorphic(word,pattern))
                result.push_back(word);
        }
        return result;
    }
    bool isIsomorphic(string s,string t)
    {
        if (s.size()!=t.size())
            return false;
        map<char,char>s_map;
        map<char,char>t_map;
        for (int i=0;i<s.size();i++)
        {
            if (!s_map.count(s[i]))
                s_map[s[i]]=t[i];
            else
            {
                //這裡寫continue而不是直接省略更加節省時間,可以結合具體案例看一下。
                if (s_map[s[i]]==t[i])
                    continue;
                else
                    return false;
            }
            if (t_map.count(t[i]))
            {
                if (t_map[t[i]]!=s[i])
                    return false;
            }
            else
                t_map[t[i]]=s[i];
        }
        return true;
    }
};

總結: