package com.heu.wsq.leetcode.arr;
/**
* 面试题 16.15. 珠玑妙算
* @author wsq
* @date 2021/1/26
* 珠玑妙算游戏(the game of master mind)的玩法如下。
* 计算机有4个槽,每个槽放一个球,颜色可能是红色(R)、黄色(Y)、绿色(G)或蓝色(B)。例如,计算机可能有RGGB 4种(槽1为红色,槽2、3为绿色,槽4为蓝色)。作为用户,你试图猜出颜色组合。打个比方,你可能会猜YRGB。要是猜对某个槽的颜色,则算一次“猜中”;要是只猜对颜色但槽位猜错了,则算一次“伪猜中”。注意,“猜中”不能算入“伪猜中”。
* 给定一种颜色组合solution和一个猜测guess,编写一个方法,返回猜中和伪猜中的次数answer,其中answer[0]为猜中的次数,answer[1]为伪猜中的次数。
*
* 示例:
* 输入: solution="RGBY",guess="GGRR"
* 输出: [1,1]
* 解释: 猜中1次,伪猜中1次。
*
* 链接:https://leetcode-cn.com/problems/master-mind-lcci
*/
public class MasterMind {
/**
* 1.使用color数组保存颜色对应的数量
* 2.若对应位置元素相同,则算一次猜中
* 3.若对应位置元素不同,则分别针对s、g元素再colors数组中进行判断,
* 遇见一个s元素,如果colors[s]小于0,则算一次伪猜中,并会将colors对应的元素加1,
* 遇见一个g元素,如果colors[g]大于0,则算一次伪猜中,并会将colors对应的元素减1,
* @param solution
* @param guess
* @return
*/
public int[] masterMind(String solution, String guess) {
int[] res = {0, 0};
int[] colors = new int[4];
int n = solution.length();
for(int i = 0; i < n; i++){
char s = solution.charAt(i);
char g = guess.charAt(i);
if(s == g){
res[0]++;
}else{
if(colors[getPos(s)] < 0){
res[1]++;
}
colors[getPos(s)]++;
if(colors[getPos(g)] > 0){
res[1]++;
}
colors[getPos(g)]--;
}
}
return res;
}
private int getPos(char c){
int pos;
if(c == 'R'){
pos = 0;
}else if(c == 'Y'){
pos = 1;
}else if(c == 'G'){
pos = 2;
}else {
pos = 3;
}
return pos;
}
}
面试题 16.15. 珠玑妙算
最新推荐文章于 2024-07-23 15:33:41 发布