forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
bulls-and-cows.cpp
45 lines (43 loc) · 1.15 KB
/
bulls-and-cows.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Time: O(n)
// Space: O(10) = O(1)
// One pass solution.
class Solution {
public:
string getHint(string secret, string guess) {
unordered_map<char, int> lookup;
int A = 0, B = 0;
for (int i = 0; i < size(secret); ++i) {
const char s = secret[i];
const char g = guess[i];
if (s == g) {
++A;
} else {
B += int(lookup[s]++ < 0) + int(lookup[g]-- > 0);
}
}
return to_string(A).append("A").append(to_string(B)).append("B");
}
};
// Two pass solution.
class Solution2 {
public:
string getHint(string secret, string guess) {
unordered_map<char, int> lookup;
int A = 0, B = 0;
for (const auto& s : secret) {
++lookup[s];
}
for (const auto& g : guess) {
if (lookup[g]) {
--lookup[g];
++B;
}
}
for (int i = 0; i < size(secret); ++i) {
if (secret[i] == guess[i]) {
++A, --B;
}
}
return to_string(A).append("A").append(to_string(B)).append("B");
}
};