力扣题-12.8
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:299. 猜数字游戏
解题思想:进行遍历,统计完全相同的数字和不相同的数字即可,然后统计不相同的数字在秘密数字和猜测数字中共同出现的次数
class Solution(object):def getHint(self, secret, guess):""":type secret: str:type guess: str:rtype: str"""A = 0B = 0count_secret = {}count_guess = {}for i in range(len(secret)):if secret[i] == guess[i]:A += 1else:count_secret[secret[i]] = count_secret.get(secret[i], 0) + 1count_guess[guess[i]] = count_guess.get(guess[i], 0) + 1for key, value in count_secret.items():if key in count_guess:B += min(value, count_guess[key])return str(A) + 'A' + str(B) + 'B'
class Solution {
public:string getHint(string secret, string guess) {int A = 0;int B = 0;std::unordered_map<char, int> count_secret;std::unordered_map<char, int> count_guess;for (int i = 0; i < secret.length(); ++i) {if (secret[i] == guess[i]) {A += 1;} else {count_secret[secret[i]] = count_secret[secret[i]] + 1;count_guess[guess[i]] = count_guess[guess[i]] + 1;}}for (const auto& entry : count_secret) {char key = entry.first;int value = entry.second;if (count_guess.find(key) != count_guess.end()) {B += std::min(value, count_guess[key]);}}return std::to_string(A) + "A" + std::to_string(B) + "B";}
};