> 文章列表 > leetcode 珠玑妙算

leetcode 珠玑妙算

leetcode 珠玑妙算

题目

珠玑妙算游戏(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次。
提示:

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/master-mind-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解思路

  • 伪猜中包含猜中的次数,需要减去猜中的次数才是真的伪猜中次数
  • 猜中的次数就进行遍历,遍历过之后进行标记,找到后直接跳出第二层循环。

代码

class Solution {
public:vector<int> masterMind(string solution, string guess) {int n = solution.size();vector<int> answer(2,0);set<char> hash;set<char> hash2;for(int i=0;i<n;i++){if(solution[i]==guess[i]){answer[0]++;}hash.insert(solution[i]);hash2.insert(guess[i]);}vector<bool> visited(n,false);for(int i=0;i<n;i++){for(int j=0;j<n;j++){if(guess[i]==solution[j] && !visited[j]){answer[1]++;visited[j] = true;break;}}}answer[1] = answer[1] - answer[0];return answer;}
};