跳到主要内容

299.猜数字游戏

链接:299.猜数字游戏
难度:Medium
标签:哈希表、字符串、计数
简介:给你一个秘密数字 secret 和朋友猜测的数字 guess ,请你返回对朋友这次猜测的提示。

题解 1 - typescript

  • 编辑时间:2021-11-08
  • 执行用时:100ms
  • 内存消耗:40.2MB
  • 编程语言:typescript
  • 解法介绍:遍历。
function getHint(secret: string, guess: string): string {
const n = secret.length;
let a = 0;
let b = 0;
const map: Record<string, number> = {};
const set = new Set<number>();
for (let i = 0; i < n; i++) {
const ch1 = secret[i];
const ch2 = guess[i];
if (ch1 === ch2) {
a++;
set.add(i);
} else map[ch1] = (map[ch1] ?? 0) + 1;
}
for (let i = 0; i < n; i++) {
if (set.has(i)) continue;
const ch2 = guess[i];
if (map[ch2]) {
b++;
map[ch2]--;
}
}
return `${a}A${b}B`;
}

题解 2 - python

  • 编辑时间:2024-03-10
  • 执行用时:68ms
  • 内存消耗:16.65MB
  • 编程语言:python
  • 解法介绍:遍历。
class Solution:
def getHint(self, secret: str, guess: str) -> str:
s1 = []
s2 = []
n = len(secret)
x = y = 0
for i in range(n):
if secret[i] == guess[i]:
x += 1
else:
s1.append(secret[i])
s2.append(guess[i])
for num in s1:
if num in s2:
y += 1
s2.remove(num)
return f'{x}A{y}B'