leetcode
leetcode 2801 ~ 2850
珠玑妙算

珠玑妙算

难度:

标签:

题目描述

The Game of Master Mind is played as follows:

The computer has four slots, and each slot will contain a ball that is red (R). yellow (Y). green (G) or blue (B). For example, the computer might have RGGB (Slot #1 is red, Slots #2 and #3 are green, Slot #4 is blue).

You, the user, are trying to guess the solution. You might, for example, guess YRGB.

When you guess the correct color for the correct slot, you get a "hit:' If you guess a color that exists but is in the wrong slot, you get a "pseudo-hit:' Note that a slot that is a hit can never count as a pseudo-hit.

For example, if the actual solution is RGBY and you guess GGRR, you have one hit and one pseudo-hit. Write a method that, given a guess and a solution, returns the number of hits and pseudo-hits.

Given a sequence of colors solution, and a guess, write a method that return the number of hits and pseudo-hit answer, where answer[0] is the number of hits and answer[1] is the number of pseudo-hit.

Example:

Input:  solution="RGBY",guess="GGRR"
Output:  [1,1]
Explanation:  hit once, pseudo-hit once.

Note:

  • len(solution) = len(guess) = 4
  • There are only "R","G","B","Y" in solution and guess.

代码结果

运行时间: 24 ms, 内存: 16.5 MB


// 思路:
// 1. 使用 Java Stream API 计算猜中和伪猜中的次数。
// 2. 使用 IntStream 对 solution 和 guess 进行遍历,计算命中的数量。
// 3. 使用 groupingBy 计算各颜色出现的次数,统计伪猜中的数量。

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class MasterMindStream {
    public int[] masterMind(String solution, String guess) {
        int hit = (int) IntStream.range(0, solution.length())
                .filter(i -> solution.charAt(i) == guess.charAt(i))
                .count();

        Map<Character, Long> solutionMap = IntStream.range(0, solution.length())
                .mapToObj(i -> solution.charAt(i))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        Map<Character, Long> guessMap = IntStream.range(0, guess.length())
                .mapToObj(i -> guess.charAt(i))
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        int pseudoHit = solutionMap.keySet().stream()
                .mapToInt(k -> Math.min(solutionMap.getOrDefault(k, 0L), guessMap.getOrDefault(k, 0L)).intValue())
                .sum() - hit;

        return new int[]{hit, pseudoHit};
    }
}

解释

方法:

该题解采用两步骤来计算猜中和伪猜中的次数。首先,通过 zip 函数和列表推导式比较 solution 和 guess 中相同位置的字符,计算完全匹配(即猜中)的次数。然后,使用 collections.Counter 来统计 solution 和 guess 中每种字符的出现频率。通过遍历 solution 的字符频率字典,使用 min 函数比较同一字符在 solution 和 guess 中出现的次数,得到该字符可能的最大匹配数,包括完全匹配和位置错误的匹配。最后,将总匹配数减去完全匹配数,得到伪猜中的次数。

时间复杂度:

O(n)

空间复杂度:

O(1)

代码细节讲解

🦆
在计算伪猜中的次数时,为什么选择使用两个Counter来计算每个字符的出现频率而不是其他方法?
使用两个Counter来计算每个字符的出现频率可以有效、简洁地处理字符统计问题。Counter的使用可以自动为每个字符计数,并处理不存在的字符(计数为0),从而简化代码和逻辑。相比于手动维护字典或数组来进行频率统计,使用Counter可以减少代码量和出错机率,提升开发效率。此外,Counter提供的方法(如min操作)可以直接应用于两个计数器,便于比较和计算最小值,这对于本题中计算潜在匹配数是非常有用的。
🦆
为什么在计算总匹配次数时,只考虑了solution中的字符键而没有考虑guess中独有的字符键?
在计算总匹配次数时,考虑solution中的字符键是因为我们需要确定这些字符在guess中的出现情况来计算匹配数。如果一个字符仅在guess中出现而不在solution中,它不会对匹配结果产生影响,因为没有相对应的solution字符与之匹配。因此,专注于solution的字符键可以有效地计算所有可能的匹配数,包括正确和错误位置的匹配。这种方法确保了算法效率和准确性。
🦆
如何处理solution或guess输入的错误情况,例如长度不为4或包含非法字符?
处理输入错误的一种方法是在函数开始时添加输入验证。可以检查solution和guess的长度确保它们均为4。同时,还可以检查每个字符串只包含允许的字符集(例如,仅限特定颜色的字符)。如果任何验证失败,则函数可以抛出异常或返回一个错误信息。这种方法可以确保进入主算法逻辑之前,所有输入都是有效的,从而避免运行时错误和逻辑错误。

相关问题