Leetcode 299. Bulls and Cows

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Bulls and Cows

2. Solution

  • Version 1
class Solution {
public:
    string getHint(string secret, string guess) {
        int bull = 0;
        int cow = 0;
        int length = secret.length();
        for(int i = 0; i < length; i++) {
            if(secret[i] == guess[i]) {
                bull++;
            }
        }
        sort(secret.begin(), secret.end());
        sort(guess.begin(), guess.end());
        int indexSecret = 0;
        int indexGuess = 0;
        while(indexSecret != length && indexGuess != length) {
            if(secret[indexSecret] == guess[indexGuess]) {
                indexSecret++;
                indexGuess++;
                cow++;
            }
            else if(secret[indexSecret] > guess[indexGuess]){
                indexGuess++;
            }
            else {
                indexSecret++;
            }
        }
        cow -= bull;
        return to_string(bull) + "A" + to_string(cow) + "B";
    }
};
  • Version 2
class Solution {
public:
    string getHint(string secret, string guess) {
        int bull = 0;
        int cow = 0;
        int length = secret.length();
        map secretMap;
        map guessMap;
        for(int i = 0; i < length; i++) {
            if(secret[i] == guess[i]) {
                bull++;
            }
            else {
                if(secretMap[guess[i]] > 0) {
                    cow++;
                    secretMap[guess[i]]--;
                }
                else {
                    guessMap[guess[i]]++;
                }
                if(guessMap[secret[i]] > 0) {
                    cow++;
                    guessMap[secret[i]]--;
                }
                else {
                    secretMap[secret[i]]++;
                }
            }
        }
        return to_string(bull) + "A" + to_string(cow) + "B";
    }
};

Reference

  1. https://leetcode.com/problems/bulls-and-cows/description/

你可能感兴趣的:(Leetcode 299. Bulls and Cows)