题目

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:

  1. Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
  2. Output: ["mee","aqq"]
  3. Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}.
  4. "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:

  1. Input: words = ["a","b","c"], pattern = "a"
  2. 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

  1. class Solution {
  2. public List<String> findAndReplacePattern(String[] words, String pattern) {
  3. List<String> ans = new ArrayList<>();
  4. for (String word : words) {
  5. if (judge(word, pattern)) ans.add(word);
  6. }
  7. return ans;
  8. }
  9. private boolean judge(String word, String pattern) {
  10. if (word.length() != pattern.length()) return false;
  11. Map<Character, Character> dict = new HashMap<>();
  12. for (int i = 0; i < word.length(); i++) {
  13. char c1 = word.charAt(i);
  14. char c2 = pattern.charAt(i);
  15. if (!dict.containsKey(c1) && dict.containsValue(c2)) {
  16. return false;
  17. } else if (!dict.containsKey(c1)) {
  18. dict.put(c1, c2);
  19. } else if (dict.get(c1) != c2) {
  20. return false;
  21. }
  22. }
  23. return true;
  24. }
  25. }