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"
相关推荐
2401_87294509几秒前
【补题】Codeforces Round 735 (Div. 2) C. Mikasa
算法
叫我:松哥2 分钟前
基于网络爬虫的在线医疗咨询数据爬取与医疗服务分析系统,技术采用django+朴素贝叶斯算法+boostrap+echart可视化
人工智能·爬虫·python·算法·django·数据可视化·朴素贝叶斯
Star在努力9 分钟前
14-C语言:第14天笔记
c语言·笔记·算法
赴3352 小时前
Numpy 库 矩阵数学运算,点积,文件读取和保存等
人工智能·算法·numpy·random·dot
自由随风飘2 小时前
机器学习-SVM支持向量机
算法·机器学习·支持向量机
屁股割了还要学3 小时前
【C语言进阶】柔性数组
c语言·开发语言·数据结构·c++·学习·算法·柔性数组
草莓熊Lotso3 小时前
【LeetCode刷题指南】--有效的括号
c语言·数据结构·其他·算法·leetcode·刷题
Alla T3 小时前
【通识】算法案例
算法
Electrolux4 小时前
你敢信,不会点算法没准你赛尔号都玩不明白
前端·后端·算法
天天开心(∩_∩)4 小时前
代码随想录算法训练营第三十一天
算法