4 ms C++, using counters


  • 1
    D
    class Solution {
    public:
        string getHint(string secret, string guess) {
            int countS[10], countG[10];
            fill_n(countS,10,0);
            fill_n(countG,10,0);
            
            int i, len=guess.size(), ACnt=0, BCnt=0;
            for(i=0; i<len;++i)
            {
                if(guess[i]==secret[i]) ++ACnt;
                else
                {
                    ++countG[guess[i] -'0'];
                    ++countS[secret[i]-'0'];
                }
            }
            for(i=0;i<10;++i)
                 BCnt += min(countS[i], countG[i]);
            
            return to_string(ACnt) + 'A'+ to_string(BCnt) + 'B';    
        }
    };
    

    Another one to use one counter array

    class Solution {
    public:
        string getHint(string secret, string guess) {
            int i, len=secret.size(), aCnt=0, bCnt=0, sCnt[10];
            for(fill_n(sCnt, 10, 0), i=0; i<len;++i)
            {
                if(secret[i]==guess[i]) ++aCnt;
                else
                {
                    if( sCnt[guess[i]-'0']-- > 0)  ++bCnt;
                    if( sCnt[secret[i]-'0']++ <0)  ++bCnt;
                }
            }
            return to_string(aCnt) + 'A' + to_string(bCnt) + 'B';
        }
    };

Log in to reply
 

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