leetcode 299. Bulls and Cows

野性酷女 2022-07-26 11:18 233阅读 0赞

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called “bulls”) and how many digits match the secret number but locate in the wrong position (called “cows”). Your friend will use successive guesses and hints to eventually derive the secret number.

For example:

  1. Secret number: "1807"
  2. Friend's guess: "7810"

Hint: 1 bull and 3 cows. (The bull is 8 , the cows are 0 , 1 and 7 .)

Write a function to return a hint according to the secret number and friend’s guess, use A to indicate the bulls and B to indicate the cows. In the above example, your function should return "1A3B".

Please note that both secret number and friend’s guess may contain duplicate digits, for example:

  1. Secret number: "1123"
  2. Friend's guess: "0111"

In this case, the 1st 1 in friend’s guess is a bull, the 2nd or 3rd 1 is a cow, and your function should return "1A1B" .

You may assume that the secret number and your friend’s guess only contain digits, and their lengths are always equal.

  1. class Solution {
  2. string my_itoa(int n)
  3. {
  4. if (n == 0)
  5. return "0";
  6. string re;
  7. while (n != 0)
  8. {
  9. re.insert(re.begin(), n % 10 + '0');
  10. n /= 10;
  11. }
  12. return re;
  13. }
  14. public:
  15. string getHint(string secret, string guess) {
  16. int bull = 0,cow=0;
  17. map<char, int>cnt1, cnt2;
  18. for (int i = 0; i < secret.length(); i++)
  19. {
  20. if (secret[i] == guess[i])
  21. bull++;
  22. else
  23. {
  24. cnt1[secret[i]]++;
  25. cnt2[guess[i]]++;
  26. }
  27. }
  28. for (map<char, int>::iterator it = cnt1.begin(); it != cnt1.end(); it++)
  29. {
  30. map<char, int>::iterator itt = cnt2.find(it->first);
  31. if (itt != cnt2.end())
  32. cow += itt->second < it->second ? itt->second : it->second;
  33. }
  34. string hint;
  35. hint += my_itoa(bull) + 'A' + my_itoa(cow) + 'B';
  36. return hint;
  37. }
  38. };

accept

其实这题给hint裁结果比较有意思

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode299. 猜数字游戏

    你正在和你的朋友玩 [猜数字(Bulls and Cows)][Bulls and Cows]游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字