-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_299.java
More file actions
49 lines (46 loc) · 1.41 KB
/
Copy pathP_299.java
File metadata and controls
49 lines (46 loc) · 1.41 KB
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
42
43
44
45
46
47
48
49
package leetcode.easy;
public class P_299 {
public String getHint(String secret, String guess) {
int bulls = 0;
int cows = 0;
final int[] numbers = new int[10];
for (int i = 0; i < secret.length(); i++) {
final int s = secret.charAt(i) - '0';
final int g = guess.charAt(i) - '0';
if (s == g) {
bulls++;
} else {
if (numbers[s] < 0) { cows++; }
if (numbers[g] > 0) { cows++; }
numbers[s]++;
numbers[g]--;
}
}
return bulls + "A" + cows + 'B';
}
public String getHintBF(String secret, String guess) {
final int n = secret.length();
final int[] freq = new int[10];
final boolean[] seen = new boolean[n];
for (char c : secret.toCharArray()) {
freq[c - '0']++;
}
int bulls = 0;
int cows = 0;
for (int i = 0; i < n; i++) {
if (secret.charAt(i) == guess.charAt(i)) {
bulls++;
freq[secret.charAt(i) - '0']--;
seen[i] = true;
}
}
for (int i = 0; i < n; i++) {
final int curr = guess.charAt(i) - '0';
if (!seen[i] && freq[curr] > 0) {
cows++;
freq[curr]--;
}
}
return bulls + "A" + cows + 'B';
}
}