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"
相关推荐
weixin199701080164 分钟前
[特殊字符] 1688开放平台API Sign签名算法详解(Java / Python / PHP 实现)
java·python·算法
未若君雅裁16 分钟前
JVM 垃圾回收算法与分代回收机制
java·jvm·算法
智者知已应修善业22 分钟前
【51单片机初始化D5-D8亮,每按键按下D1到D4全亮,再按下恢复,如此循环】2024-3-26
c++·经验分享·笔记·算法·51单片机
8Qi81 小时前
LeetCode 4:寻找两个正序数组的中位数 —— 二分查找法
java·算法·leetcode·职场和发展·二分查找
8Qi81 小时前
LeetCode 32:最长有效括号 —— 栈 + 标记法 题解
java·数据结构·算法·leetcode·职场和发展··括号匹配
机器学习之心1 小时前
198种组合算法+优化CNN-LSTM+SHAP分析+新数据预测+多输出!深度学习可解释分析,强烈安利,粉丝必备
深度学习·算法·cnn-lstm·shap分析·198种组合算法
Tairitsu_H1 小时前
[LC优选算法#3] 滑动窗口 | 将x减到0的最⼩操作数 | ⽔果成篮 | 字⺟异位词
c++·算法·leetcode·滑动窗口
bIo7lyA8v1 小时前
算法复杂度与能耗关系的多变量分析研究的技术8
算法
洛水水2 小时前
【力扣100题】76.搜索插入位置
数据结构·算法·leetcode
Techblog of HaoWANG2 小时前
智巡守卫:多模态巡检智能体算法服务端设计与实现——基于Ollama+Qwen3.5的自动化巡检报告生成系统
运维·人工智能·算法·目标检测·自动化·边缘计算