299. Bulls and Cows
来源:互联网 发布:hydra windows版使用 编辑:程序博客网 时间:2024/04/29 13:29
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 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.
class Solution {public:string getHint(string secret, string guess) {int lens = secret.size();int leng = guess.size();if (lens != leng){return "";}vector<int> hash(10,0);int bull = 0, cow = 0;for (int i = 0; i < lens; i++){hash[secret[i]-'0']++;}for (int i = 0; i < leng; i++){if (guess[i] == secret[i]){bull++;hash[guess[i]-'0']--;}}//等公牛选完才能选母牛for (int i = 0; i < leng; i++){if (guess[i] != secret[i]){if (hash[guess[i] - '0']>0){cow++;hash[guess[i] - '0']--;}}}string res;res += to_string(bull) + "A" + to_string(cow) + "B";return res;}};
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- 299. Bulls and Cows
- Android Volley的理解
- iOS AudioSession详解 Category选择 听筒扬声器切换kAudioSessionCategory_MediaPlayback
- Android Fragment 真正的完全解析(下)
- #include sys/xxx.h头文件 UNIX头文件
- 读书笔记-java网络编程-5URL和URI-x-www-form-urlencoded
- 299. Bulls and Cows
- 规则流的应用及说明
- sql中With AS语句的用法
- weka和matlab完成完整分类实验
- BeanUtils制作自定义的转换器
- #if 与#endif
- 计算广告中的名词解释
- 7.5.实验 解题参考
- 配置sonar、jenkins进行持续审查