299. Bulls and Cows - CPP - Solution


  • -1
    Y
    // 299. Bulls and Cows
    // https://leetcode.com/problems/bulls-and-cows/
    #include <iostream>
    #include <string> // required for string container
    #include <algorithm> // required for min() function
    #include <unordered_map> // required for unordered_map container
    using namespace std;
    class Solution {
    public:
    	string getHint(const string& secret, const string& guess) {
    		string result = "";
    		unordered_map<char, size_t> secretMap;
    		unordered_map<char, size_t> guessMap;
    		size_t numOfA = 0;
    		size_t numOfB = 0;
    		for (size_t i = 0; i < secret.size() && i < guess.size(); ++i) {
    			++secretMap[secret[i]];
    			++guessMap[guess[i]];
    			if (secret[i] == guess[i]) {
    				++numOfA;
    			}
    		}
    		for (const auto& i : secretMap) {
    			if (guessMap.count(i.first)) {
    				numOfB += min(i.second, guessMap[i.first]);
    			}
    		}
    		numOfB -= numOfA;
    		result.append(to_string(numOfA));
    		result.push_back('A');
    		result.append(to_string(numOfB));
    		result.push_back('B');
    		return result;
    	}
    };
    int main(int argc, const char** agrv) {
    	Solution solution;
    	string secret = "1123";
    	string guess = "0111";
    	cout << solution.getHint(secret, guess) << '\n';
    	getchar();
    	return 0;
    }

Log in to reply
 

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