File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -35,4 +35,36 @@ public List<String> findAndReplacePattern(String[] words, String pattern) {
3535 return result ;
3636 }
3737 }
38+
39+ public static class Solution2 {
40+ public List <String > findAndReplacePattern (String [] words , String pattern ) {
41+ List <String > result = new ArrayList <>();
42+ for (String word : words ) {
43+ if (matches (word , pattern )) {
44+ result .add (word );
45+ }
46+ }
47+ return result ;
48+ }
49+
50+ private boolean matches (String word , String pattern ) {
51+ Map <Character , Character > map1 = new HashMap <>();//word -> p
52+ Map <Character , Character > map2 = new HashMap <>();//p -> word
53+ for (int i = 0 ; i < pattern .length (); i ++) {
54+ if (!map1 .containsKey (word .charAt (i ))) {
55+ map1 .put (word .charAt (i ), pattern .charAt (i ));
56+ }
57+ if (map1 .containsKey (word .charAt (i )) && map1 .get (word .charAt (i )) != pattern .charAt (i )) {
58+ return false ;
59+ }
60+ if (!map2 .containsKey (pattern .charAt (i ))) {
61+ map2 .put (pattern .charAt (i ), word .charAt (i ));
62+ }
63+ if (map2 .containsKey (pattern .charAt (i )) && map2 .get (pattern .charAt (i )) != word .charAt (i )) {
64+ return false ;
65+ }
66+ }
67+ return true ;
68+ }
69+ }
3870}
You can’t perform that action at this time.
0 commit comments