C++ one pass O(N) time, easy to understand


  • 0
    B

    amap[a[i] ] means when a[i]!=b[i], the count of a[i] in a;

    bmap[b[i] ] means when a[i]!=b[i], the count of b[i] in b;

    when find the corresponding value , just decrease both at the same time;

    string getHint(string secret, string guess) {
        int countBull=0, countCow = 0;
       
        int amap[10]={0}, bmap[10]={0};
        
        for(int i=0 ; i<secret.length(); i++){
            if(secret[i]==guess[i]) countBull++;
            
            else{
                    if(bmap[secret[i]-'0']>0){
                        countCow++;
                        bmap[secret[i]-'0']--;
                    }
                    else  amap[secret[i]-'0']++;
                    
                    if(amap[guess[i]-'0']>0){
                        countCow++;
                        amap[guess[i]-'0']--;
                    }
                    else bmap[guess[i]-'0']++;
                }
        }
        
        return to_string(countBull)+"A"+to_string(countCow)+"B";        
    }

  • 0

    我想问一下,这个题目就是纪录一次猜对和猜错的个数吗?是这个意思吧?


Log in to reply
 

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