C++_4ms_65.87% (O(n), O(1))


  • 0

    It should be O(3n) time complexity.

     class Solution {
     public:
     string getHint(string secret, string guess) {
        int n = secret.size();
        int bull = 0, cow = 0;
        string res;
        vector<int> times(10,0);
        
        for(int i = 0; i < n; i++){
            times[secret[i] - '0']++;
        }
        
        for(int i = 0; i < n; i++){
            if(secret[i] == guess[i]){bull++; times[guess[i] - '0']--;}
        }
        
        for(int i = 0; i < n; i++){
            if(secret[i] != guess[i] && times[guess[i] - '0'] > 0){cow++; times[guess[i] - '0']--;}
        }
        /*"1122" vs "1222"*/
    
        
        res = to_string(bull) + "A" + to_string(cow) + "B";
        return res;
    }     };

Log in to reply
 

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