Leetcode NO.299 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  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:

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.

其实本题的题目要求稍微有点模糊。。读了半天才读懂,是先要找相同元素,比如“1123”和"0111",其中相同元素是都有两个"1",但是这两个“1”中,其中一个是Bulls一个是Cows。。

然后再说说算法,这个要进行两次遍历:

  • 第一次是分别遍历两个string,然后将元素放入分别对应的hashmap(key是char,即0~9, value是该char出线的次数)。。然后顺便找secrect[i] = guess[i]出现过几次,这个就是Bulls
  • 第二次是遍历两个hashmap,寻找他们相同字母出现次数之和,该值为(Bulls + Cows),然后减去之前的Bulls就是Cows的书目
  • 需要注意,这里面因为只有'0' - '9'这10个digit,所以不需要定义一个unordered_map,直接定义一个数组就可以解决,代码如下:
class Solution {
public:
    string getHint(string secret, string guess) {
        vector sec(10);
        vector gue(10);
        int A = 0;      // bull
        for (int i = 0; i < secret.length(); ++i) {
            sec[secret[i] - '0']++;
            gue[guess[i] - '0']++;
            if (guess[i] == secret[i]) {
                ++A;
            }
        }
        int summation = 0;
        for (int i = 0; i < 10; ++i) {
            summation += min(sec[i], gue[i]);
        }
        return to_string(A) + "A" + to_string(summation - A) + "B";
    }
};


你可能感兴趣的:(Leetcode)