Easy java solution with comments


  • 0
    D

    public class Solution {
    public String getHint(String secret, String guess) {

        //Initialize a hashmap to store indices and corresponding boolean value of both secret and guess
        HashMap<Integer,Boolean> secret_map=new HashMap<Integer,Boolean>();
        HashMap<Integer,Boolean> guess_map=new HashMap<Integer,Boolean>();
        
        //initialize the maps
        for(int i=0;i<secret.length();i++)
        {
            secret_map.put(i,false);
            guess_map.put(i,false);
        }
        
        //variable to keep track of bulls and cows
        int bulls=0;
        int cows=0;
        
        //to keep track of bulls
        for(int i=0;i<guess.length();i++)
        {
            if(guess.charAt(i)==secret.charAt(i))
            {
                //increment bulls and update hashmaps of both secret and guess
                bulls++;
                secret_map.put(i,true);
                guess_map.put(i,true);
            }
        }
        
        //to keep track of cows
        for(int i=0;i<guess.length();i++)
        {
                int j=0;
                
                while(j<secret.length() )
                {
                    //only to keep track of cows
                    if(i!=j)
                    {
                        //check only those which are neither bull nor cow
                        if(guess.charAt(i)==secret.charAt(j) && !secret_map.get(j) && !guess_map.get(i))
                        {
                            //update cows and corresponding hashmaps
                            cows++;
                            secret_map.put(j,true);
                            guess_map.put(i,true);
                        }
                    }
                    
                    
                    j++;
                }
            
        }
        
        //update the value of the string
        String answer = Integer.toString(bulls)+"A"+Integer.toString(cows)+"B";
        
        return answer;
        
    }
    

    }


Log in to reply
 

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