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;
        }
    };
  • 相关阅读:
    递推&&矩阵加速
    洛谷 P1217 [USACO1.5]回文质数 Prime Palindromes
    总结一下当前阶段我认为比较常用的字符串操作
    关于递归与递推
    P1553 数字反转(升级版)
    关于C++读入数字按位取出与进制转换问题
    一本通题库 1058:求一元二次方程
    弄懂goroutine调度原理
    线程实现模型
    gin-jwt对API进行权限控制
  • 原文地址:https://www.cnblogs.com/csudanli/p/5311710.html
Copyright © 2011-2022 走看看