LeetCode 890. Find and Replace Pattern
原题链接在这里:https://leetcode.com/problems/find-and-replace-pattern/
题目:
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 order.
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
题解:
In order to check if the word mattches pattern, it needs to find bi-directional matching relationship.
If each pair of char match each other using 2 maps, then return true.
Time Complexity: O(n*m). n = words.length. m is average length of word in words.
Space: O(m). regardless res.
AC Java:
1 class Solution { 2 public List<String> findAndReplacePattern(String[] words, String pattern) { 3 List<String> res = new ArrayList<>(); 4 if(pattern == null || pattern.length() == 0 || words == null || words.length == 0){ 5 return res; 6 } 7 8 for(String word : words){ 9 if(isMatch(word, pattern)){ 10 res.add(word); 11 } 12 } 13 14 return res; 15 } 16 17 private boolean isMatch(String s, String p){ 18 if(s.length() != p.length()){ 19 return false; 20 } 21 22 Map<Character, Character> map1 = new HashMap<>(); 23 Map<Character, Character> map2 = new HashMap<>(); 24 25 for(int i = 0; i<s.length(); i++){ 26 char sChar = s.charAt(i); 27 char pChar = p.charAt(i); 28 if(map1.containsKey(sChar) && map1.get(sChar)!=pChar){ 29 return false; 30 } 31 32 if(map2.containsKey(pChar) && map2.get(pChar)!=sChar){ 33 return false; 34 } 35 36 map1.put(sChar, pChar); 37 map2.put(pChar, sChar); 38 } 39 40 return true; 41 } 42 }