[Leetcode] 299. Bulls and Cows 解题报告

来源:互联网 发布:宋徽宗瘦金体字帖 淘宝 编辑:程序博客网 时间:2024/06/11 12:55

题目

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的数量,并且将secret中不是bull的位置上的字符存放在哈希表中;第二遍扫描的过程中跳过bull位置,然后在哈希表中查找是否还有相对应的字符,如果有则说明是一个cow,否则跳过。最后统计一下bull和cow的数量,返回即可。感觉这道题目考查的应该是哈希表的使用。我实现的算法的时间复杂度是O(n),空间复杂度也是O(n),其中n是secret和guess字符串的长度。

代码

class Solution {public:    string getHint(string secret, string guess) {        int bull = 0, cow = 0;        unordered_map<char, int> hash;        for (int i = 0; i < secret.length(); ++i) {            if (secret[i] == guess[i]) {                ++bull;                guess[i] = '#';            }            else {                ++hash[secret[i]];            }        }        for (int i = 0; i < guess.length(); ++i) {            if (guess[i] != '#') {                if (hash.count(guess[i]) > 0 && hash[guess[i]] > 0) {                    --hash[guess[i]];                    ++cow;                }            }        }        return to_string(bull) + 'A' + to_string(cow) + 'B';    }};

原创粉丝点击