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

    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:

    Secret number:  "1807"
    Friend's guess: "7810"
    

    Hint: 1 bull and 3 cows. (The bull is 8, the cows are 01 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:

    Secret number:  "1123"
    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.

      这个题目大致的意思是:两个人,一个人出题,猜题人知道这个数的长度。然后出题人告诉猜题人的答案中有多少猜对的数字(不仅仅是数字对,而且对应的位置也对)记为bull,也就是返回的字符串中为A前面的数字加1,也告诉猜题人有多少数字存在出题人给的数中但是位置不对记为cow,也就是返回的字符串中为B前面的数字加1.

      注意:重复的数字,如举得例子中“1123”,“0111”,只能有一个cow,最后一个’1‘,或者倒数第二个’1‘中,只有一个能记为cow。另外一个不能记为cow,是因为出题人给的数中,只有一个位置不对的‘1’,所以应该返回的字符串是“1A1B”。

      

    class Solution {
    public:
        string getHint(string secret, string guess) {
        int group[10] = {};
        for (auto e : secret)
            group[e - 48] += 1;
        unsigned len = secret.size();
        int cnta = 0, cntb = 0;
        for (unsigned i = 0;i < len;++i)
        {
            if(group[guess[i]-48]>0)
            {
                --group[guess[i] - 48];
                ++cnta;
            }
            if (guess[i] == secret[i])
                ++cntb;
        }
        string str = to_string(cntb) + "A" + to_string(cnta-cntb) + "B";
        return str;
        }
    };
  • 相关阅读:
    PCB 规则引擎之脚本语言JavaScript应用评测
    PCB 挺有意思的基数排序----C#代码实现
    PCB NOSQL MongoDb MI流程指示数据存储结构
    PCB javascript解析Gerber274X格式实现方法
    PCB javascript解析钻孔(Excellon)格式实现方法
    PCB 围绕CAM自动化,打造PCB规则引擎
    PCB Genesis拼SET画工艺边 实现方法(一)
    约瑟夫环的三种解法
    Microsoft edge真香!
    商城规格参数
  • 原文地址:https://www.cnblogs.com/csudanli/p/5311710.html
Copyright © 2011-2022 走看看