Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
bulls-and-cows.cpp 1.33 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-09-12 11:43 +08:00 . Rename bulls-and-cow.cpp to bulls-and-cows.cpp
// Time: O(n)
// Space: O(10) = O(1)
// One pass solution.
class Solution {
public:
string getHint(string secret, string guess) {
unordered_map<char, int> s_lookup, g_lookup;
int A = 0, B = 0;
const int n = min(secret.length(), guess.length());
for (int i = 0; i < n; ++i) {
const char s = secret[i];
const char g = guess[i];
if (s == g) {
++A;
} else {
(s_lookup[g] > 0) ? --s_lookup[g], ++B : ++g_lookup[g];
(g_lookup[s] > 0) ? --g_lookup[s], ++B : ++s_lookup[s];
}
}
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;
}
}
const int n = min(secret.length(), guess.length());
for (int i = 0; i < n; ++i) {
if (secret[i] == guess[i]) {
++A, --B;
}
}
return to_string(A).append("A").append(to_string(B)).append("B");
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助