LeetCode/solutions/299. Bulls and Cows.md
2022-10-26 22:48:25 +08:00

55 lines
1.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [299. Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)
# 思路
A的个数比较简单只需要挨个位置比较即可。B的个数需要先用一个数组记录secret中各数字出现的个数需排除A情况再遍历一遍看guess中的数字是否在secret中出现过若是则B个数加一。
# C++
```C++
class Solution {
public:
string getHint(string secret, string guess) {
int a = 0, b = 0;
vector<int>mp(10, 0);
for(int i = 0; i < secret.size(); i++){
if(secret[i] != guess[i]) mp[secret[i] - '0']++;
}
for(int i = 0; i < secret.size(); i++){
if(secret[i] == guess[i]) a++;
else if(mp[guess[i] - '0'] > 0){
b++;
mp[guess[i] - '0']--;
}
}
return to_string(a) + "A" + to_string(b) + "B";
}
};
```
也可以只遍历一遍:
```C++
class Solution {
public:
string getHint(string secret, string guess) {
int a = 0, b = 0;
vector<int>mp1(10, 0);
vector<int>mp2(10, 0);
for(int i = 0; i < secret.size(); i++){
if(secret[i] != guess[i]){
mp1[secret[i] - '0']++;
mp2[guess[i] - '0']++;
}else{
a++;
}
}
for(int i = 0; i < 10; i++){
b += min(mp1[i], mp2[i]);
}
return to_string(a) + "A" + to_string(b) + "B";
}
};
```