Share my 8ms c++ solution


  • 0
    Y
    class Solution {
    public:
        string getHint(string secret, string guess) {
            int cbull = 0;
            int ccow = 0;
            int arr[10]  = {0}; 
            int arr2[10]  = {0}; 
            stringstream res;
            string result = "";
            for(int i = 0; i < secret.size(); i++) {
                arr[secret[i] - '0'] ++;
                if(secret[i] == guess[i]) {
                    cbull ++;
                    arr[secret[i] - '0'] --;
                }
                else{
                    arr2[guess[i] - '0'] ++;
                    if(arr[guess[i] - '0'] != 0) {
                        ccow ++;
                        arr[guess[i] - '0'] --;
                        arr2[guess[i] - '0'] --;
                    }
                    if(arr2[secret[i] - '0'] != 0) {
                        ccow ++;
                        arr2[secret[i] - '0'] --;
                        arr[secret[i] - '0'] --;
                    }
                }
            }
            res<<cbull<<"A"<<ccow<<"B"; 
            res>>result;
           return result; 
        }
    };

Log in to reply
 

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