Easy and Simple to Understand Java Solution


  • 1
    C

    I used a HashMap to store the frequency of each digit and count1 gives us the Bull count and count2 gives us the Cows count

     public class Solution {
            public String getHint(String secret, String guess) {
                char arr1[] = secret.toCharArray();
                char arr2[] = guess.toCharArray();
                if(arr1.length == arr2.length)
                {
                    int count1=0,count2=0;
                    StringBuffer result = new StringBuffer(arr1.length);
                    HashMap<Character,Integer> hmap = new HashMap<Character,Integer>();
                    for(int i=0;i<arr1.length;i++)
                    {
                        if(!hmap.containsKey(arr1[i]))
                        hmap.put(arr1[i],1);
                        else
                        hmap.put(arr1[i],hmap.get(arr1[i])+1);
                    }
                     for(int j=0; j < arr2.length ; j++)
                    {
                        if(arr1[j]==arr2[j])
                        {
                        count1++;
                        hmap.put(arr1[j],hmap.get(arr1[j])-1);
                        }
                    }
                     for(int j=0; j < arr2.length ; j++)
                    {
                        if(arr1[j]!=arr2[j] && hmap.containsKey(arr2[j]) && hmap.get(arr2[j])!=0)
                        {
                        hmap.put(arr2[j],hmap.get(arr2[j])-1);
                        count2++;
                        }
                    }
                    
                    result.append(count1);
                    result.append('A');
                    result.append(count2);
                    result.append('B');
                  return  result.toString();
                }
                return null;
            }
        }`

Log in to reply
 

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