Skip to content

Commit d0b1f56

Browse files
refactor 890
1 parent 2844116 commit d0b1f56

File tree

1 file changed

+24
-45
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+24
-45
lines changed

src/main/java/com/fishercoder/solutions/_890.java

+24-45
Original file line numberDiff line numberDiff line change
@@ -7,53 +7,32 @@
77
import java.util.Map;
88
import java.util.Set;
99

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-
*/
3110
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;
11+
public static class Solution1 {
12+
public List<String> findAndReplacePattern(String[] words, String pattern) {
13+
List<String> result = new ArrayList<>();
14+
for (String word : words) {
15+
Map<Character, Character> map = new HashMap<>();
16+
Set<Character> set = new HashSet<>();
17+
boolean match = true;
18+
for (int i = 0; i < pattern.length(); i++) {
19+
if (map.containsKey(pattern.charAt(i))) {
20+
if (word.charAt(i) != map.get(pattern.charAt(i))) {
21+
match = false;
22+
break;
23+
}
24+
} else {
25+
map.put(pattern.charAt(i), word.charAt(i));
26+
if (!set.add(word.charAt(i))) {
27+
match = false;
28+
}
29+
}
30+
}
31+
if (match) {
32+
result.add(word);
33+
}
4434
}
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);
35+
return result;
5436
}
55-
}
56-
return result;
5737
}
58-
}
5938
}

0 commit comments

Comments
 (0)