1 Star 0 Fork 0

yuhang2__2/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
bulls-and-cows.cpp 1.15 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 5年前 . Update 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> 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");
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/yuhang2__2/LeetCode-Solutions.git
git@gitee.com:yuhang2__2/LeetCode-Solutions.git
yuhang2__2
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助