「每日LeetCode」2021年4月17日

本文最后更新于:2023年3月19日 晚上

面试题 16.15. 珠玑妙算

面试题 16.15. 珠玑妙算

珠玑妙算游戏(the game of master mind)的玩法如下。
计算机有 4 个槽,每个槽放一个球,颜色可能是红色(R)、黄色(Y)、绿色(G)或蓝色(B)。例如,计算机可能有 RGGB 4 种(槽 1 为红色,槽 2、3 为绿色,槽 4 为蓝色)。作为用户,你试图猜出颜色组合。打个比方,你可能会猜 YRGB。要是猜对某个槽的颜色,则算一次“猜中”;要是只猜对颜色但槽位猜错了,则算一次“伪猜中”。注意,“猜中”不能算入“伪猜中”。
给定一种颜色组合solution和一个猜测guess,编写一个方法,返回猜中和伪猜中的次数answer,其中answer[0]为猜中的次数,answer[1]为伪猜中的次数。
示例:

1
2
3
输入: solution="RGBY",guess="GGRR"
输出: [1,1]
解释: 猜中1次,伪猜中1次。

提示:

  • len(solution) = len(guess) = 4
  • solutionguess仅包含"R","G","B","Y"这 4 种字符

思路

先遍历两个字符比较有没有完全猜中的,直接计数并删掉对应字符,源字符串中不相同的加入 map 中,再遍历一次剩余的猜测字符,如果在 map 中有则伪猜中次数加一,map 删去对应的次数。返回结果。

解答

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
/**
* @param {string} solution
* @param {string} guess
* @return {number[]}
*/
var masterMind = function (solution, guess) {
let res1 = 0,
res2 = 0;
b;
guess = guess.split("");
const map = new Map();
for (let i = 0, j = 0; i < solution.length; i++, j++) {
const char = solution[i];
if (map.has(char)) map.set(char, map.get(char) + 1);
else map.set(char, +1);
if (guess[j] === solution[i]) {
res1++;
if (map.get(char) === 1) map.delete(char);
else if (map.get(char) > 1) map.set(char, map.get(char) - 1);
guess.splice(j, 1);
j--;
}
}
for (let i = 0; i < guess.length; i++) {
const char = guess[i];
if (map.has(char)) res2++;
if (map.get(char) === 1) map.delete(char);
else if (map.get(char) > 1) map.set(char, map.get(char) - 1);
}
return [res1, res2];
};