Skip to content

Commit 9ac886c

Browse files
add a solution for 299
1 parent af69b65 commit 9ac886c

File tree

1 file changed

+40
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+40
-0
lines changed

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

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.fishercoder.solutions;
22

3+
import java.util.HashMap;
4+
import java.util.Map;
5+
36
public class _299 {
47
public static class Solution1 {
58
public String getHint(String secret, String guess) {
@@ -21,4 +24,41 @@ public String getHint(String secret, String guess) {
2124
return bulls + "A" + cows + "B";
2225
}
2326
}
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+
}
2464
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy