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;
        }
    };
  • 相关阅读:
    数据库为什么要分区分表
    搜索时 搜索条件在被搜索范围内
    Spring RestTemplet https请求
    微信三方平台接入
    在安装RedisDesktopManager的时候遇到 .dll文件缺失解决办法
    Spring中常见的设计模式——装饰者模式
    Spring中常见的设计模式——适配器模式
    Spring中常见的设计模式——模板模式
    Spring中常见的设计模式——策略模式
    Spring中常见的设计模式——代理模式
  • 原文地址:https://www.cnblogs.com/csudanli/p/5311710.html
Copyright © 2011-2022 走看看