Solution URL
https://leetcode.com/submissions/detail/416210633/
代码
class Solution {
public String getHint(String secret, String guess) {
//ans: Solution.
int bulls = 0;
int cows = 0;
//use hashmap to store character and its frequence in secret.
HashMap<Character, Integer> map = new HashMap<>();
for(char s: secret.toCharArray()){
map.put(s, map.getOrDefault(s, 0) + 1);
}
//iterate the guess string
int len = guess.length();
for(int i = 0; i < len; i++){
char g = guess.charAt(i);
//if character exists in secret
if(map.containsKey(g)){
//check index matches or not
//if matches, then it is bull
if(g == secret.charAt(i)){
bulls++;
//to check whether it is miscount as a cow
if(map.get(g) <= 0){
cows--;
}
}else{
//update cows
if(map.get(g) > 0){
cows++;
}
}
//update the frequence of current char
map.put(g, map.get(g) - 1);
}
}
return bulls + "A" + cows + "B";
}
}