O(n) Time C++ Solution - Very Easy


  • -1
    M
    int arr[256];
    string getHint(string secret, string guess) {
        int a = 0,b = 0;
        int len = secret.length();
        for(int i = 0; i < len; i++){
            arr[secret[i]]++;
        }
        for(int i = 0; i < len; i++){
            if(secret[i] == guess[i]){
                a++;
                arr[guess[i]]--;
            }
        }
        for(int i = 0; i < len; i++){
            if(arr[guess[i]] > 0 && guess[i] != secret[i]){
                b++;
                arr[guess[i]]--;
            }
        }
        
        char *str = new char[4];
        sprintf(str, "%dA%dB", a,b);
        return str;
    }

Log in to reply
 

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