zoukankan      html  css  js  c++  java
  • [LeetCode] Bulls and Cows

    Bulls and Cows

    You are playing the following Bulls and Cows game with your friend: You write a 4-digit secret number and ask your friend to guess it, each time your friend guesses a number, you give a hint, the hint tells your friend how many digits are in the correct positions (called "bulls") and how many digits are in the wrong positions (called "cows"), your friend will use those hints to find out the secret number.

    For example:

    Secret number:  1807
    Friend's guess: 7810
    

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

    According to Wikipedia: "Bulls and Cows (also known as Cows and Bulls or Pigs and Bulls or Bulls and Cleots) is an old code-breaking mind or paper and pencil game for two or more players, predating the similar commercially marketed board game Mastermind. The numerical version of the game is usually played with 4 digits, but can also be played with 3 or any other number of digits."

    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.

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

    Credits:
    Special thanks to @jeantimex for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

     1 class Solution {
     2 public:
     3     string getHint(string secret, string guess) {
     4         int cntA = 0, cntB = 0;
     5         unordered_map<char, int> hash;
     6         vector<bool> tag(secret.size(), false);
     7         for (auto a : secret) {
     8             ++hash[a];
     9         };
    10         for (int i = 0; i < secret.size(); ++i) {
    11             if (secret[i] == guess[i]) {
    12                 ++cntA;
    13                 --hash[secret[i]];
    14                 tag[i] = true;
    15             }
    16         }
    17         for (int i = 0; i < guess.size(); ++i) {
    18             if (!tag[i] && hash[guess[i]] > 0) {
    19                 ++cntB;
    20                 --hash[guess[i]];
    21             }
    22         }
    23         return to_string(cntA) + "A" + to_string(cntB) + "B";
    24     }
    25 };
  • 相关阅读:
    论频谱中负频率成分的物理意义(转载)
    VS2008的glaux库
    通过域名显示IP列表
    Shader errorX3205的解决
    Curl, Divergence, Circulation
    关于FIONREAD命令的作用
    Cairngorm的结构及开发使用(2)(转)
    结合Flex Builder和Flash CS4制作一个中国地图的应用(转)
    大型高并发高负载网站的系统架构(转)
    Cairngorm的结构及开发使用(4)(转)
  • 原文地址:https://www.cnblogs.com/easonliu/p/4926337.html
Copyright © 2011-2022 走看看