-
Notifications
You must be signed in to change notification settings - Fork 109
/
299-bulls-and-cows.cpp
55 lines (54 loc) · 1.63 KB
/
299-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
46
47
48
49
50
51
52
53
54
55
// Time: O(N), Space: O(1)
class Solution {
public:
string getHint(string secret, string guess) {
int bulls = 0;
int cows = 0;
for (int i = 0; i < secret.size(); i++) {
if (secret[i] == guess[i]) {
secret[i] = '$';
guess[i] = '$';
bulls++;
}
}
for (int k = 0; k < secret.size(); k++) {
if (secret[k] == '$') continue;
int idx = guess.find_first_of(secret[k], 0);
if (idx != string::npos) {
cows++;
guess[idx] = '!';
}
}
return to_string(bulls) + "A" + to_string(cows) + "B";
}
};
// Time: O(N), Space: O(N)
class Solution {
public:
string getHint(string secret, string guess) {
if (secret.size() == 0) return "";
unordered_multiset<char> guessSet;
vector<bool> marked(secret.size(), false);
int bulls = 0;
int cows = 0;
for (int i = 0; i < secret.size(); i++) {
if (secret[i] == guess[i]) {
marked[i] = true;
bulls++;
} else {
guessSet.insert(guess[i]);
}
}
for (int k = 0; k < secret.size(); k++) {
if (!marked[k]) {
auto it = guessSet.find(secret[k]);
if (it != guessSet.end()) {
cows++;
guessSet.erase(it);
}
}
}
string toReturn = to_string(bulls) + "A" + to_string(cows) + "B";
return toReturn;
}
};