Not one pass but easy to understand Java solution using 2 hashmaps


  • 0
    T
    public class Solution {
        public String getHint(String secret, String guess) {
            int bulls = 0;
            int cows = 0;
            Map<Character, Integer> secretMap = new HashMap<>();
            Map<Character, Integer> guessMap = new HashMap<>();
            
            for(int i = 0;i<secret.length();i++){
                char a = secret.charAt(i);
                char b = guess.charAt(i);
                if(a==b){
                    bulls++;
                }else{
                    secretMap.put(a, secretMap.getOrDefault(a,0)+1);
                    guessMap.put(b, guessMap.getOrDefault(b,0)+1);
                }
            }
            
            for(char c: secretMap.keySet()){
                if(guessMap.containsKey(c)){
                    int val = secretMap.get(c);
                    for(int i = 0;i<val;i++){
                        if(guessMap.get(c)==0) break;
                        else{
                            guessMap.put(c, guessMap.get(c)-1);
                            cows++;
                        }
                    }    
                }
                
            }
            
            return ""+bulls+"A"+cows+"B";
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.