|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.List; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +/** |
| 11 | + * 890. Find and Replace Pattern |
| 12 | + * |
| 13 | + * You have a list of words and a pattern, and you want to know which words in words matches the pattern. |
| 14 | + * 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. |
| 15 | + * (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.) |
| 16 | + * Return a list of the words in words that match the given pattern. |
| 17 | + * You may return the answer in any order. |
| 18 | + * |
| 19 | + * Example 1: |
| 20 | + * |
| 21 | + * Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb" |
| 22 | + * Output: ["mee","aqq"] |
| 23 | + * Explanation: "mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. |
| 24 | + * "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, |
| 25 | + * since a and b map to the same letter. |
| 26 | + * |
| 27 | + * Note: |
| 28 | + * 1 <= words.length <= 50 |
| 29 | + * 1 <= pattern.length = words[i].length <= 20 |
| 30 | + */ |
| 31 | +public class _890 { |
| 32 | + public static class Solution1 { |
| 33 | + public List<String> findAndReplacePattern(String[] words, String pattern) { |
| 34 | + List<String> result = new ArrayList<>(); |
| 35 | + for (String word : words) { |
| 36 | + Map<Character, Character> map = new HashMap<>(); |
| 37 | + Set<Character> set = new HashSet<>(); |
| 38 | + boolean match = true; |
| 39 | + for (int i = 0; i < pattern.length(); i++) { |
| 40 | + if (map.containsKey(pattern.charAt(i))) { |
| 41 | + if (word.charAt(i) != map.get(pattern.charAt(i))) { |
| 42 | + match = false; |
| 43 | + break; |
| 44 | + } |
| 45 | + } else { |
| 46 | + map.put(pattern.charAt(i), word.charAt(i)); |
| 47 | + if (!set.add(word.charAt(i))) { |
| 48 | + match = false; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + if (match) { |
| 53 | + result.add(word); |
| 54 | + } |
| 55 | + } |
| 56 | + return result; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments