My 4ms cpp code, O(n) time


  • 0
    C
    class Solution {
    public:
        
        string getHint(string secret, string guess)
        {
            int secret_cnt[10] = {0};
            int guess_cnt[10] = {0};
            
            int bull_cnt = 0, cow_cnt = 0;
            
            for(int i=0; i<secret.size(); i++)
            {
                char secret_ch = secret[i] - '0';
                char guess_ch = guess[i] - '0';
                
                secret_cnt[secret_ch]++;
                guess_cnt[guess_ch]++;
                
                if(secret_ch == guess_ch)
                {
                    bull_cnt++;
                    secret_cnt[secret_ch]--;
                    guess_cnt[guess_ch]--;
                    continue;
                }
                
                if(secret_cnt[guess_ch])
                {
                    secret_cnt[guess_ch]--;
                    guess_cnt[guess_ch]--;
                    cow_cnt++;
                }
                
                if(guess_cnt[secret_ch])
                {
                    guess_cnt[secret_ch]--;
                    secret_cnt[secret_ch]--;
                    cow_cnt++;
                }
            }
            
            ostringstream s;
            s << bull_cnt << "A" << cow_cnt << "B";
            return s.str();
        }
    };

  • 0
    D

    can you explain the following.. why

            char secret_ch = secret[i] - '0';
            char guess_ch = guess[i] - '0';
    

    " - '0' ". What does it do?


Log in to reply
 

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