File tree

3 files changed

+86
-1
lines changed

3 files changed

+86
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#include <algorithm>
2+
#include <vector>
3+
#include <unordered_map>
4+
#include <iostream>
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
string getHint(string secret, string guess) {
10+
const int len = secret.size();
11+
unordered_map<char, int> dict;
12+
for (auto& ch : secret)
13+
{
14+
dict[ch]++;
15+
}
16+
int total = 0;
17+
for (auto& ch : guess)
18+
{
19+
if (dict[ch] > 0)
20+
total++;
21+
dict[ch]--; /* 当前字符用1次后, 就从哈希表中删掉它 */
22+
}
23+
int bulls = 0;
24+
for (int i = 0; i < len; i++)
25+
{
26+
if (secret[i] == guess[i]) /* 对比两个字符串, 统计位置相同的字符的数量 */
27+
bulls++;
28+
}
29+
return to_string(bulls) + "A" + to_string(total - bulls) + "B";
30+
}
31+
};
32+
33+
// Test
34+
int main()
35+
{
36+
Solution sol;
37+
string secret = "1122", guess = "2211";
38+
auto res = sol.getHint(secret, guess);
39+
cout << res << endl;
40+
41+
return 0;
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <algorithm>
2+
#include <vector>
3+
#include <unordered_map>
4+
#include <iostream>
5+
#include <cstring>
6+
using namespace std;
7+
8+
class Solution {
9+
public:
10+
string getHint(string secret, string guess) {
11+
const int len = secret.size();
12+
int dict[11]; /* 数组模拟哈希表, 由于全是数字, 所以哈希表的key是0~9, 共10个, 预留1个 */
13+
memset(dict, 0, sizeof(dict));
14+
for (auto& ch : secret)
15+
{
16+
dict[ch - '0']++;
17+
}
18+
int total = 0;
19+
for (auto& ch : guess)
20+
{
21+
if (dict[ch - '0'] > 0)
22+
total++;
23+
dict[ch - '0']--; /* 当前字符用1次后, 就从哈希表中删掉它 */
24+
}
25+
int bulls = 0;
26+
for (int i = 0; i < len; i++)
27+
{
28+
if (secret[i] == guess[i]) /* 对比两个字符串, 统计位置相同的字符的数量 */
29+
bulls++;
30+
}
31+
return to_string(bulls).append("A") + to_string(total - bulls).append("B");
32+
}
33+
};
34+
35+
// Test
36+
int main()
37+
{
38+
Solution sol;
39+
string secret = "1122", guess = "2211";
40+
auto res = sol.getHint(secret, guess);
41+
cout << res << endl;
42+
43+
return 0;
44+
}
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#include <algorithm>
22
#include <vector>
3-
#include <unordered_map>
43
#include <iostream>
54
using namespace std;
65

0 commit comments

Comments
 (0)