1
1
package com .fishercoder .solutions ;
2
2
3
+ import java .util .HashMap ;
4
+ import java .util .Map ;
5
+
3
6
public class _299 {
4
7
public static class Solution1 {
5
8
public String getHint (String secret , String guess ) {
@@ -21,4 +24,41 @@ public String getHint(String secret, String guess) {
21
24
return bulls + "A" + cows + "B" ;
22
25
}
23
26
}
27
+
28
+ public static class Solution2 {
29
+ /**
30
+ * My completely original solution on 12/24/2021.
31
+ */
32
+ public String getHint (String secret , String guess ) {
33
+ int bulls = 0 ;
34
+ int cows = 0 ;
35
+ boolean [] bulled = new boolean [secret .length ()];
36
+ Map <Integer , Integer > map = new HashMap <>();
37
+ for (int i = 0 ; i < secret .length (); i ++) {
38
+ if (secret .charAt (i ) == guess .charAt (i )) {
39
+ bulled [i ] = true ;
40
+ bulls ++;
41
+ }
42
+ }
43
+ for (int i = 0 ; i < secret .length (); i ++) {
44
+ if (!bulled [i ]) {
45
+ int num = Character .getNumericValue (secret .charAt (i ));
46
+ map .put (num , map .getOrDefault (num , 0 ) + 1 );
47
+ }
48
+ }
49
+ for (int i = 0 ; i < secret .length (); i ++) {
50
+ if (!bulled [i ]) {
51
+ int num = Character .getNumericValue (guess .charAt (i ));
52
+ if (map .getOrDefault (num , 0 ) > 1 ) {
53
+ map .put (num , map .get (num ) - 1 );
54
+ cows ++;
55
+ } else if (map .getOrDefault (num , 0 ) == 1 ) {
56
+ map .remove (num );
57
+ cows ++;
58
+ }
59
+ }
60
+ }
61
+ return bulls + "A" + cows + "B" ;
62
+ }
63
+ }
24
64
}
0 commit comments