Leetcode 299. Bulls and Cows

Problem

You are playing the Bulls and Cows game with your friend.

You write down a secret number and ask your friend to guess what the number is. When your friend makes a guess, you provide a hint with the following info:

  • The number of "bulls", which are digits in the guess that are in the correct position.
  • The number of "cows", which are digits in the guess that are in your secret number but are located in the wrong position. Specifically, the non-bull digits in the guess that could be rearranged such that they become bulls.

Given the secret number secret and your friend's guess guess, return the hint for your friend's guess.

The hint should be formatted as "xAyB", where x is the number of bulls and y is the number of cows. Note that both secret and guess may contain duplicate digits.

Algorithm

Use three list to record the state, if a number is used just ignore it.

Code

python3 复制代码
class Solution:
    def getHint(self, secret: str, guess: str) -> str:
        slen = len(secret)
        bulls = [0] * slen
        cows = [0] * slen
        used = [0] * slen
        for i in range(slen):
            if secret[i] == guess[i]:
                bulls[i] = 1
                used[i] = 1
        for i in range(slen):
            if not bulls[i]:
                for j in range(slen):
                    if i != j and not bulls[j] and not used[j]:
                        if secret[j] == guess[i]:
                            cows[i] = 1
                            used[j] = 1
                            break
        
        return str(sum(bulls)) + "A" + str(sum(cows)) + "B"
相关推荐
十八岁讨厌编程2 小时前
【算法训练营Day26】动态规划part2
算法·动态规划
智者知已应修善业2 小时前
【C++无数组矩阵对角线平均值保留2位小数】2022-11-18
c语言·c++·经验分享·笔记·算法·矩阵
papership3 小时前
【入门级-算法-6、排序算法: 计数排序】
数据结构·算法·排序算法
pengpeng023 小时前
力扣每日一题 611. 有效三角形的个数
算法·leetcode·职场和发展
2401_840105203 小时前
GESP C++5级 2025年6月编程2题解:最大公因数
数据结构·c++·算法
未知陨落3 小时前
LeetCode:56.子集
算法·leetcode·深度优先
PAK向日葵3 小时前
【算法导论】一道涉及到溢出处理的笔试题
算法·面试
哈泽尔都4 小时前
运动控制教学——5分钟学会样条曲线算法!(三次样条曲线,B样条曲线)
c++·人工智能·算法·机器学习·matlab·贪心算法·机器人
小镇学者4 小时前
【NOI】在信奥赛中 什么是函数交互题?
算法
未知陨落4 小时前
LeetCode:62.N皇后
算法·leetcode