File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ #leetcode 890
2
+ ```
3
+ //思路是保证对应下标的权重是一样的,只需要比较权重就可以判断是否符合规则
4
+ class Solution {
5
+ public static List<String> findAndReplacePattern(String[] words, String pattern) {
6
+ List<String> result = new ArrayList<>();//返回结果
7
+ char [] patternArray = pattern.toCharArray();//字符串转字符数组
8
+ for(int i=0;i<words.length;i++)//遍历每一个words中的字符串
9
+ {
10
+ char [] wordArray = words[i].toCharArray();
11
+ boolean flag = true;//标记,为true说明匹配
12
+ if(wordArray.length == patternArray.length)//匹配肯定长度要相等
13
+ {
14
+ HashMap<Character,Character> judge = new HashMap<>();//hashmap1
15
+ HashMap<Character,Character> judge2 = new HashMap<>();//反向比较hashmap2
16
+ for(int j=0;j<pattern.length();j++)//遍历模式串中的每一个字符
17
+ {
18
+ if(judge.containsKey(patternArray[j]) == false)
19
+ {//判断key中是否存在这个字符,不存在hashmap1就添加key-value
20
+ judge.put(patternArray[j],wordArray[j]);
21
+ if(judge2.containsKey(wordArray[j]) == false)
22
+ {//这个if else的作用就是思路中的hashmap2的作用了
23
+ judge2.put(wordArray[j],patternArray[j]);//不存在就添加
24
+ }else {
25
+ if(judge2.get(wordArray[j]) != patternArray[j]){
26
+ flag = false;//存在的话就去判断是不是相等的,不相等就不匹配
27
+ break;
28
+ }
29
+ }
30
+ }else {//存在的话 去hashmap中找这个字符与现有的字符是否相等
31
+ //不相等,说明存在了(a-c a-b 一个a对应两个字符)直接返回false,不匹配
32
+ if(judge.get(patternArray[j]) != wordArray[j])
33
+ {
34
+ flag = false;
35
+ break;
36
+ }
37
+ }
38
+ }
39
+ if(flag)
40
+ {
41
+ result.add(words[i]);
42
+ }
43
+ }
44
+
45
+ }
46
+ return result;
47
+ }
48
+ }
49
+ ```
You can’t perform that action at this time.
0 commit comments