0890. Find and Replace Pattern (M)

Find and Replace Pattern (M)

题目

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.

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.

Example 2:

Input: words = ["a","b","c"], pattern = "a"
Output: ["a","b","c"]

Constraints:

  • 1 <= pattern.length <= 20
  • 1 <= words.length <= 50
  • words[i].length == pattern.length
  • pattern and words[i] are lowercase English letters.

题意

在一个单词列表中找到所有符合pattern形式的单词。

思路

问题可以转化为找到所有的单词,使这个单词中的字符能与pattern中的字符建立起一对一的映射。


代码实现

Java

class Solution {
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> ans = new ArrayList<>();

        for (String word : words) {
            if (judge(word, pattern)) ans.add(word);
        }
        
        return ans;
    }

    private boolean judge(String word, String pattern) {
        if (word.length() != pattern.length()) return false;
        
        Map<Character, Character> dict = new HashMap<>();

        for (int i = 0; i < word.length(); i++) {
            char c1 = word.charAt(i);
            char c2 = pattern.charAt(i);
            
            if (!dict.containsKey(c1) && dict.containsValue(c2)) {
                return false;
            } else if (!dict.containsKey(c1)) {
                dict.put(c1, c2);
            } else if (dict.get(c1) != c2) {
                return false;
            }
        }

        return true;
    }
}
posted @ 2021-05-21 21:30  墨云黑  阅读(35)  评论(0编辑  收藏  举报