Easy to understand Java Solution using arrays


  • 0
    E

    We start by getting the count of the bulls first which we can obtain by comparing all the characters at the same positions- if they are equal we increase the bull count by 1, else we get the count of the remaining digits for the 2 Strings in 2 different arrays by storing the count in their indexes. Next, we take the minimum of the array values as we don't want to count the repeated characters

    public class Solution {
        public String getHint(String secret, String guess) {
            int b=0,c=0;
            int arr1[]=new int[10];
            int arr2[]=new int[10];
            for(int i=0;i<secret.length();i++){
                char ch1=secret.charAt(i);
                char ch2=guess.charAt(i);
                if(ch1==ch2){
                    b++;
                }
                else{
                    arr1[ch1-'0']++;
                    arr2[ch2-'0']++;
                }
            }
            for(int i=0;i<10;i++){
                c+=Math.min(arr1[i],arr2[i]);
            }
            return(b+""+"A"+c+""+"B");
        }
    }
    

Log in to reply
 

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