-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution299.java
34 lines (30 loc) · 981 Bytes
/
Solution299.java
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
package leetcode.hashmap;
import java.util.HashMap;
public class Solution299 {
public String getHint(String secret, String guess) {
String res = "%dA%dB";
int a = 0;
char[] charArray = guess.toCharArray();
char[] sCharArray = secret.toCharArray();
for (int i = 0; i < sCharArray.length; i++) {
if (sCharArray[i] == charArray[i]) {
a++;
sCharArray[i] = charArray[i] = ' ';
}
}
int b = 0;
HashMap<Character, Integer> charCount = new HashMap<>();
for (char c : charArray) {
if (c != ' ') {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
}
for (char c : sCharArray) {
if (charCount.containsKey(c) && charCount.get(c) > 0) {
b++;
charCount.put(c, charCount.get(c) - 1);
}
}
return String.format(res, a, b);
}
}