珠玑妙算
2023-07-14 本文已影响0人
红树_
题目
珠玑妙算游戏(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次。
解题思路
- 哈希表:使用数组作哈希表进行计数,分别计算两种情况猜中和伪猜中的结果。
哈希表
class Solution {
public int[] masterMind(String solution, String guess) {
int[] ans = new int[2];
//考虑哈希表
int[] hash = new int[26];
char[] cs = solution.toCharArray();
char[] gs = guess.toCharArray();
boolean[] res = new boolean[4];
for(int i = 0; i < 4; i++) {
if(gs[i] == cs[i]) {
ans[0]++;
res[i] = true;
}
else hash[cs[i]-'A'] ++;
}
for(int i = 0; i < 4; i++) {
if(!res[i] && hash[gs[i]-'A'] > 0) {
ans[1]++;
hash[gs[i]-'A']--;
}
}
return ans;
}
}
复杂度分析
- 时间复杂度:
O(n)
,n
为字符串长度,一重循环遍历。 - 空间复杂度:
O(k)
,字符串最多由26个字母组成,哈希数组计数空间固定为k=26
。