One pass, one array


  • 0
    Z
    class Solution {
    public:
        string getHint(string secret, string guess) {
            int cnt[10] = {};
            int n = secret.length();
            int a = 0, b = 0;
            for(int i = 0; i < n; i++){
                if(secret[i] == guess[i]){
                    a++;
                }else{
                    b = (cnt[secret[i] - '0'] < 0)? b + 1 : b;
                    cnt[secret[i] - '0']++;
                    
                    b = (cnt[guess[i] - '0'] > 0)? b + 1 : b;
                    cnt[guess[i] - '0']--;
                }
            }
            return to_string(a) + "A" + to_string(b) + "B";
        }
    };

Log in to reply
 

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