leetcode-890. 查找和替换模式

原始思路

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public List<String> findAndReplacePattern(String[] words, String pattern) {
List<String> result = new ArrayList<>();
Map<Character, Character> map = new HashMap<>();
Map<Character, Character> rmap = new HashMap<>();
for (int i = 0; i < words.length; i++) {
map.clear();
rmap.clear();
if (words[i].length() != pattern.length()) {
continue;
}

boolean b = true;
for (int j = 0; j < words[i].length(); j++) {
// 进行模式比较
char chr1 = words[i].charAt(j);
char chr2 = pattern.charAt(j);
if (!map.containsKey(chr2) && !rmap.containsKey(chr1) ) {
map.put(chr2, chr1);
rmap.put(chr1, chr2);
}else {
if (map.containsKey(chr2) && map.get(chr2) != chr1) {
b = false;
break;
}

if (rmap.containsKey(chr1) && rmap.get(chr1) != chr2) {
b = false;
break;
}
}
}

if (b) {
result.add(words[i]);
}
}

return result;
}
}