O(n) time; O(1) space


  • 4
    S

    public class Solution {
    public String getHint(String secret, String guess) {
    int bulls=0;
    int cows=0;
    int[] count=new int[10];

        /*loop once 
           1231
           0230
           
           0231
           1230
           
           gor guess, count--; for secret, count++
        */
        for(int i=0;i<secret.length();i++){
            int s=secret.charAt(i)-'0';
            int g=guess.charAt(i)-'0';
            if(s==g){
                bulls++;
            }else{
                if(count[g]>0){
                    cows++;
                }
                if(count[s]<0){
                    cows++;
                }
                count[g]--;
                count[s]++;
            }
        }
        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.