Bulls and Cows

2019-05-25 22:51:25 浏览数 (1)

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
class Solution {
public:
    string getHint(string secret, string guess) {
        int bull = 0;
        int cow = 0;
        int length = secret.length();
        map<char, int> secretMap;
        map<char, int> 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";
    }
};

0 人点赞