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 分钟前
Localisation using the Appearance of Prior Structure 论文阅读
论文阅读·算法·机器人·自动驾驶
阿巴~阿巴~3 分钟前
深入解析素数筛法:从埃氏筛到欧拉筛的算法思想与实现
开发语言·c++·算法
浅安的邂逅1 小时前
Linux 文件操作-标准IO函数4-fseek设置文件偏移量、ftell获取当前偏移量、rewind使文件偏移量(为0)定位到开头
linux·运维·算法
onlyzzr1 小时前
Leetcode Hot100 第65题 10.正则表达式匹配
算法·leetcode·职场和发展
没有续篇诗.2 小时前
第七章 排序算法法法
算法·排序算法
veejaLiu2 小时前
LeetCode 30.串联所有单词的子串
java·学习·算法·leetcode·职场和发展·刷题
Echo木4 小时前
DeepSeek-R1学习
人工智能·学习·算法
WispX8886 小时前
【JVM】GC 常见问题
java·jvm·算法
安忘8 小时前
LeetCode-274.H 指数
算法·leetcode·职场和发展
xxxmmc8 小时前
Leetcode 160 Intersection of Two Linked Lists
算法·leetcode·双指针